﻿
    /////////////////////////////////////////////////////////
    //
    //  MU Work Point Global Function 
    //
    //   Author    : Niyom R. & Khanoksin S.
    //   Date      : About 01/02/2011
    //
    /////////////////////////////////////////////////////////


    /* Modification History
     *   - Adding to hide form when do not select permission (Reseach and Culture Mission)
     *   Date-Time    : 23/01/2013 10:00 A.M.
         By           : Niyom R.

     *   - Adding delete item of point common function 
     *   Date-Time    : 28/01/2013 13.43 P.M.
         By           : Niyom R.

     *   - Adding form input date or period date (getDateInput function).
     *   Date-Time    : 06/02/2013 11.36 A.M.
         By           : Niyom R.
        
     *   - Adding edit and delete item in time series (Colleciton of item).
     *   Date-Time    : 12/03/2013 11.36 A.M.
         By           : Niyom R.
     *   - Adding ProcessCallback function and ProcessReport for final action after database or any process success.
     *   Date-Time    : 12/03/2013 11.36 A.M.
         By           : Niyom R.
         
     */


//Global var
var _gob_MSId = null; //Used by checkChangePeriodDate to loadFrmEditin each IU mission
 var _labelDate1 = null; //Used by getDateInput function
 var _labelDate2 = null; //USed by getDateInput function'
 var _gob_initStartDate = null; //Used by getDateInput function assign initStartDate compare startDate for check start date modifying.
 var _gob_initSEndDate = null; //Used by getDateInput function assign init endDate  compare endDate for check modified end modifying.
 var _gob_startDate = null; //Used by getDateInput function
 var _gob_endDate = null; //USed by getDateInput function'
 var _gob_indexDay = null;
 var _gob_PTGStatus = null; //Used by submitEditWorkDateCase3 function and Assign by openEdit['mission']'

 function setInitGlobalVar(){
     _gob_MSId = null; //Used by checkChangePeriodDate to loadFrmEditin each IU mission
     _labelDate1 = null; //Used by getDateInput function
     _labelDate2 = null; //USed by getDateInput function'
     _gob_initStartDate = null; //Used by getDateInput function assign initStartDate compare startDate for check start date modifying.
     _gob_initSEndDate = null; //Used by getDateInput function assign init endDate  compare endDate for check modified end modifying.
     _gob_startDate = null; //Used by getDateInput function
     _gob_endDate = null; //USed by getDateInput function'
     _gob_indexDay = null;
     _gob_PTGStatus = null; //Used by submitEditWorkDateCase3 function and Assign by openEdit['mission']'
 }
 var _gob_messageConfirmDeleteItem = "<span style='font-weight:bold; font-size:14px;'>ยืนยันการลบรายการ</span><br/>" +
                                   "<div>" +
                                     "<div style='padding-left:30px; padding-top:5px; padding-bottom:10px'><strong>ยืนยัน</strong>การลบรายการนี้ <strong>Click</strong> ที่ปุ่ม <strong>OK</strong>,&nbsp;&nbsp;&nbsp;&nbsp;<strong>ยกเลิก</strong>การลบรายการ <strong>Click</strong> ที่ปุ่ม <strong>Cancel</strong><br/>" +
                                 "<div>";
//Global bool day to check checked day
 _gob_arr_day = new Array("daySun", "dayMon", "dayTues", "dayWednes", "dayThurs", "dayFri", "daySatur");

function MM_openBrWindow(theURL,winName,features) { //v2.0
    window.open(theURL,winName,features);
}
//<-- Swap image
function MM_swapImgRestore() { //v3.0
    var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
        if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//--> Swap image


/** ProcessCallback function
*-
**/
function ProcessCallback(_fnc, _par) {
    window[_fnc](_par);
}

//HTML.Object.Disable = true or false 
function disabledObject(_bool) {
    $('select, input, textarea, radio').each(function () {  // Disable day checkbox only case 3
        if (_bool == true) {
            $(this).attr('disabled', 'disabled');
        } else {
            $(this).removeAttr('disabled', 'disabled');
        }
    });
}

function getPeriodDateForm(_prm_start_date, _prm_end_date) {
    var _arr_rs_date = new Array();
    var _rs_period_date = "0";
    var _rs_message_date = "";
    // Parse the entries
    var _arr_date_start = _prm_start_date.split("/");
    var _arr_date_end = _prm_end_date.split("/");
    _conv_dateStart = new Date(_arr_date_start[2] - 543 + "-" + _arr_date_start[1] + "-" + _arr_date_start[0]); //Convert to right format of Date object
    _conv_dateStop = new Date(_arr_date_end[2] - 543 + "-" + _arr_date_end[1] + "-" + _arr_date_end[0]);  //Convert to right format of Date object
    //alert(_conv_dateStart + ", " + _conv_dateStop + "\nStart" + (_arr_date_start[2] - 543) + "," + _arr_date_start[1] + "," + _arr_date_start[0] + "\nEnd" + (_arr_date_end[2] - 543) + "," + _arr_date_end[1] + "," + _arr_date_end[0]);
    var _start_Date = Date.parse(_conv_dateStart);
    var _end_Date = Date.parse(_conv_dateStop);
    // Make sure they are valid
    if (isNaN(_start_Date) && isNaN(_end_Date)) {
        _rs_message_date = "Start and End date fail";
    } else if (isNaN(_start_Date)) {
        //alert("The start date provided is not valid, please enter a valid date.");
        _rs_message_date = "Start date fail";
    } else if (isNaN(_end_Date)) {
        _rs_message_date = "End date fail";
    } else {
        var _minutes = 1000 * 60;
        var _hours = _minutes * 60;
        var _days = _hours * 24;
        var _years = _days * 365;
        var _rs_period_date = ((_end_Date) - (_start_Date)) / _days;
        if (_rs_period_date < 0) {
            _rs_message_date = "End date < Start date";
        } else if (_rs_period_date == 0) {
            _rs_message_date = "Least than one";
        } 
    }
    _arr_rs_date[0] = _rs_period_date;
    _arr_rs_date[1] = _rs_message_date;
    return _arr_rs_date;
}
//<--Calendar
  /*Calendar*/
function getCalendar(_id) {
    $(_id).datepicker({
            showOn: "button",
            buttonImage: "../images/icon/calendar.gif",
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            dayNamesMin: ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'],
            isBuddhist: true,
            monthNamesShort: ['มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'],
            onSelect: function () {
                getDateProperties(_id);
            }
        });
}

function getDynamicCalendar(_id) {
    $('input[id^="' + _id + '"]').each(function () { //Loop assign datepicker to input id begining with "searchDate" string
        $(this).datepicker({
            showOn: "button",
            buttonImage: "../images/icon/calendar.gif",
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            dayNamesMin: ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'],
            isBuddhist: true,
            monthNamesShort: ['มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'],
            onSelect: function () {
                getDateProperties("#" + $(this).attr('id'));
            }
        });
    });
}
/* End calendar */

//-->  calendar

//<--Util
    function setPositionCenter(_divId) {
        var _dialogOpen = $("#" + _divId).dialog("isOpen");
        if (_dialogOpen == true) {
            $("#" + _divId).dialog("option", "position", 'center');
        }
    }
    function setChildTableHeight100Percent(_idTbChild/*Must be 9 characters*/) {
        $("table").each(function (i) {
            var _id = $(this).attr("id");
            if (_id != undefined) {
                if (_id.substr(0, 9) == _idTbChild) {
                    $(this).height(($(this).parent()).height() + 1);
                }
            }

        });
    }
    //-->Util

//<--Check box
function chkBoxAll(_nameChkBoxDivide, _tbChkList){
    //alert(document.getElementsByName(_nameChkBoxDivide));
    if(document.getElementsByName(_nameChkBoxDivide) == "[object HTMLCollection]" || document.getElementsByName(_nameChkBoxDivide) == "[object NodeList]"){
        for(i=0;i<document.getElementsByName(_nameChkBoxDivide).length; i++){
            document.getElementsByName(_nameChkBoxDivide)[i].checked = true;
            chkTr(_tbChkList, (i+1));
        }
     }else{
        document.getElementsByName(_nameChkBoxDivide).checked = true;
            chkTr(_tbChkList, (1));
     }
}
function unChkBoxAll(_nameChkBoxDivide, _tbChkList){
  if(document.getElementsByName(_nameChkBoxDivide) == "[object HTMLCollection]" || document.getElementsByName(_nameChkBoxDivide) == "[object NodeList]"/*Firefox*/){
        for(i=0; i<document.getElementsByName(_nameChkBoxDivide).length; i++){
            document.getElementsByName(_nameChkBoxDivide)[i].checked = false;
             unChkTr(_tbChkList, (i+1))
        }
     }else{
        document.getElementsByName(_nameChkBoxDivide).checked = false;
        unChkTr(_tbChkList, (1))
     }
}

//****Used by user
function validateChkBoxAll(_nameChkBoxAllMain, _nameChkBoxDivide, _tbChkList){
    if(document.getElementById(_nameChkBoxAllMain).checked == false){
        _nameChkBoxAllMain.title = "ไม่เลือกทั้งหมด";
         
        unChkBoxAll(_nameChkBoxDivide, _tbChkList);
    }else{
       _nameChkBoxAllMain.title = "เลือกทั้งหมด";
       chkBoxAll(_nameChkBoxDivide, _tbChkList);
    }
    countChkBoxToChkAll(_nameChkBoxAllMain, _nameChkBoxDivide, _tbChkList);
}
//
function validateChkBoxThis(_nameChkBoxAllMain, _nameChkBoxDivide, _idChkBoxDivide, _tbChkList, _idRow){
    var _objId =  document.getElementById(_idChkBoxDivide);
    if(_objId.checked == true){
         chkTr(_tbChkList, _idRow);
    }else{
        unChkTr(_tbChkList, _idRow);
    }
    countChkBoxToChkAll(_nameChkBoxAllMain, _nameChkBoxDivide, _tbChkList);
}
function countChkBoxToChkAll(_nameChkBoxAllMain, _nameChkBoxDivide, _tbChkList){
//Count check box
var _countChkBox = 0;
var _displayCountItem = 0;
    //alert(document.getElementsByName(_nameChkBoxDivide).length + " " + document.getElementsByName(_nameChkBoxDivide));
     if(document.getElementsByName(_nameChkBoxDivide) == "[object HTMLCollection]"/*IE*/ || document.getElementsByName(_nameChkBoxDivide) == "[object NodeList]"/*Firefox*/){
        for(i=0;i<document.getElementsByName(_nameChkBoxDivide).length; i++){
            if(document.getElementsByName(_nameChkBoxDivide)[i].checked == true){
                _countChkBox += 1;
                _displayCountItem += 1;
            }
             if(document.getElementsByName(_nameChkBoxDivide)[i].checked == false){
                _countChkBox -= 1;
            }
        }
    }else{
            if(document.getElementsByName(_nameChkBoxDivide).checked == true){
                _countChkBox += 1;
                _displayCountItem += 1;
            }
             if(document.getElementByNames(_nameChkBoxDivide).checked == false){
                _countChkBox -= 1;
            }
    }
//
    
var _rows = (document.getElementById(_tbChkList).rows.length-2); //-2 because cut off title and foot tr from table
    //alert(_countChkBox+" "+_rows + " " +_idTable);
if(_countChkBox == _rows){
    document.getElementById(_nameChkBoxAllMain).checked = true;
}
    if(_countChkBox != _rows){
    document.getElementById(_nameChkBoxAllMain).checked = false;
}
if(_displayCountItem!=0){
    $("#displayCountItem").html("รายการที่ถูกเลือก "+_displayCountItem+" รายการ");
}else{
    $("#displayCountItem").html("");
}
} 
//-->Check box

/*Show search table*/
function searchTable(_showStatus, _url, _request, _pmData) {
    var _rsPm = "";
    if(_pmData!=undefined){_rsPm = _pmData;}
            postPreloadMain();
            var _post = "action=showTable&pmData=" + (_rsPm);
        _post += _request;
            $.ajax({
                url: _url,
                context: document.body,
                type: "POST",
                data: _post,
                charset: "tis-620",
                onBlock: function () { //OnBlock
                    }, //OnBlock,
                success: function (data) {
                    $("#showTable").html(data);
                    //Sortdate
                    getCalendar("#searchDateStart");
                    getCalendar("#searchDateEnd");
                    
                    createButtonSearch();
                    /*Set height and width of child table inside the table of assignment
                    *-Height and width of child table must equar parent table
                    */
                    setChildTableHeight100Percent("tbChild_2");
                    //
             
                    //Bubble
                    bubble();
                }
            }).done(function () {
                $.unblockUI();
            });
    }
/*End search table */
    /* growlUI */
function growlUIByUser(_prmMessage, _prmStatus) {
    var _str, _iconStatus, _icon;
    if (typeof (_prmMessage) == "object") {
        _str = _prmMessage.str;
        _iconStatus = _prmMessage.icon;
    } else {
        _str = _prmMessage;
        _iconStatus = _prmStatus;
    }
    var _width = 200;
    if (_str.length > 20) {
        _width = 250;
    }else if (_str.length > 22) {
        _width = 270;
    }
    if(_iconStatus == undefined){
        _icon = '';
    }else if(_iconStatus == true){
        _icon = '<IMG border=0 src="../images/png/48x48/accept(3).png" height="48" align="absmiddle">';
    }else if(_iconStatus == false){
        _icon = '<IMG border=0 src="../images/png/48x48/remove.png" height="48" align="absmiddle">';
    } else if (_iconStatus == "delete") {
        _icon = '<IMG border=0 src="../images/png/48x48/trash_can.png" height="48" align="absmiddle">';
    } else if (_iconStatus == "loading") {
        _icon = '<IMG border=0 src="../images/icon/loading3.gif" height="48" align="absmiddle">&nbsp;&nbsp;';
    } else if (_iconStatus == 'error') {
        _icon = '<IMG border=0 src="../images/png/48x48/process_remove(1).png" height="48" align="absmiddle">';
    } else {
        _icon = _iconStatus;
    }
    if (_str.length > 22) {
        _width = 270;
    }
    $.blockUI({
        message: _icon + '&nbsp;&nbsp;' + _str,
        fadeIn: 700,
        fadeOut: 700,
        timeout: 2000,
        showOverlay: false,
        centerY: true,
        centerX: true,
        baseZ: 1500,
        css: {
            border: 'none',
            top: ($(window).height() - 50) / 2 + 'px',
            left: ($(window).width() - _width) / 2 + 'px',
            width: String(_width) + 'px',
            padding: '10px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            'khtml-border-radius': '10px',
            'border-radius': '10px',
            opacity: .8,
            color: '#fff',
            fontSize: '16px'
        }
    });

}
/********************************************Post data preload******************************************************/
    function postPreloadMain(_str) {
    if(_str == undefined){
        _str = "โปรดรอสักครู่....";
    }
    var _width = 200;
   
    $.blockUI({
        message: '<IMG border=0 src="../images/icon/loading3.gif" height="48" align="absmiddle">&nbsp;&nbsp;' + _str,
        fadeIn: 700,
        fadeOut: 700,
        showOverlay: true,
        centerY: true,
        centerX: true,
        baseZ: 2500, 
        css: {
            border: 'none',
            top: ($(window).height() - 50) / 2 + 'px',
            left: ($(window).width() - _width) / 2 + 'px',
            width: String(_width) + 'px',
            padding: '10px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            'khtml-border-radius': '10px',
            'border-radius': '10px',
            opacity: .8,
            color: '#fff',
            fontSize: '16px'
        }
    });
}
   // -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; -khtml-border-top-left-radius: 5px; border-top-left-radius: 5px; 
    function postPreload(_str) {
       
        var _width = 250;
        var _strLength = 0;
        _str = _str + ' โปรดรอสักครู่...';
        _strLength = _str.length;
        if (_strLength <= 20) {
            _width = 250;
        } else if (_strLength <= 25) {
            _width = 300;
        } else if (_strLength <= 30) {
            _width = 350;
        } else {
           _width = 400;
        }
        $.blockUI({ // BlockUI
            message: '<IMG border=0 src="../images/icon/loading3.gif" height="48" align="absmiddle">&nbsp;&nbsp;' + _str,
                        fadeOut: 700,
                        showOverlay: true,
                        centerY: true,
                        centerX: true,
                        baseZ: 3000, 
                            css: {
                            border: 'none',
                            top: ($(window).height() - 50) / 2 + 'px',
                            left: ($(window).width() - _width) / 2 + 'px',
                            width: String(_width)+'px',
                            padding: '10px',
                            backgroundColor: '#000',
                            '-webkit-border-radius': '10px',
                            '-moz-border-radius': '10px',
                            'khtml-border-radius': '10px',
                            'border-radius': '10px',
                            opacity: .8,
                            color: '#fff',
                            fontSize: '16px'
                        }
                    }); // BlockUI
}
/*******************************************End post data preload*****************************************************/
/*End growlUI */
/*Bubble*/
function bubble(){
var _switchTheme;
    $(document).ready(function () {

                //create bubble popups for each element with class "button"
                $('.bubble').CreateBubblePopup();

                for (i = 0; i < $('.bubble').length; i++) {
                    //Switch theme
                    if(i%2==0){
                        _switchTheme = 'blue';
                    }else{
                        _switchTheme = 'black';
                        }
                    //show the bubble popup with new options
                    $('#bubble_' + i).SetBubblePopupOptions({
                        position: 'left',
                        align: 'top',
                        tail : {align: 'top'},
                        innerHtmlStyle: { color: '#333333','text-align': 'center' },
                        themeName: _switchTheme,
                        themePath: '../images/jquerybubblepopup-theme',
                        mouseOver: 'show',
                        closingDelay: 0,
                        selectable: true,
                        innerHtml: $('#txtBubble_' + i).html()
                    });

                }

            });
    }
    
    /*End bubble*/
function Alert(_txtTmp) {
    var _txtArray, _text;
    _txtArray = _txtTmp.split('#');
    _text = "<div style='padding: 5px; text-align:left;' class='ui-state-error ui-corner-all' id='alertMessage'>";
    for (var i = 0; i < _txtArray.length; i++) {
        if (i == 0) {
        } else {
            if (i == 1) {
                _text += "<div style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></div><strong>-</strong> " + _txtArray[i] + "<div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            } else {
                _text += "<div style='float: left; margin-right: 0.3em; padding-left:19px;'><strong>-</strong> " + _txtArray[i] + "</div><div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            }
        }
    }
    _text = _text + "</div>";
    return _text;
}

function JSONAlert(_msg_member) {
    var _rsAlertMsg = "";
    var _HTM = "";
    _HTM = "<div style='padding: 5px; text-align:left;' class='ui-state-error ui-corner-all' id='alertMessage'>";
    for (var i = 0; i < _msg_member.length; i++) {
       
            if (i == 0) {
                _HTM += "<div style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></div><strong>-</strong> " + (_msg_member[i]) + "<div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            } else {
                _HTM += "<div style='float: left; margin-right: 0.3em; padding-left:19px;'><strong>-</strong> " + (_msg_member[i]) + "</div><div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            }
     
    }
    _rsAlertMsg = _HTM + "</div>";
    return _rsAlertMsg;
    
}

function processInterrupt(_txtTmp, _divDisplay){

        var _txtArray, _text;
    _txtArray = _txtTmp.split('#');
    _text = "<div style='padding: 5px; text-align:left;' class='ui-state-error ui-corner-all' id='alertMessage'>";
    for (var i = 0; i < _txtArray.length; i++) {
        if (i == 0) {
        } else {
            if (i == 1) {
                _text += "<div style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></div><strong>-</strong> " + _txtArray[i] + "<div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            } else {
                _text += "<div style='float: left; margin-right: 0.3em; padding-left:19px;'><strong>-</strong> " + _txtArray[i] + "</div><div style='clear:both; height:0px; line-height:0px; font-size:0px;'></div>";
            }
        }
    }
    _text = _text + "</div>";
    $.unblockUI(); // Unblock from postPreload
    $("#"+_divDisplay).append(_text);
}
//<----Construct Button
//Common button
$(function () {
    $("#button-save").button({
        icons: { primary: "ui-icon-disk" }
    });
    $("#button-save2").button({
        icons: { primary: "ui-icon-disk" }
    });
    $("#button-reset").button({
        icons: { primary: "ui-icon-refresh" }
    });
    $("#button-reset2").button({
        icons: { primary: "ui-icon-refresh" }
    });
    $("#button-close").button({
        icons: { primary: "ui-icon-circle-close" }
    });
    $("#button-close2").button({
        icons: { primary: "ui-icon-circle-close" }
    });
    $("#button-insert").button({
        icons: { primary: "ui-icon-plusthick" }
    });
    $("#button-import").button({
        icons: {
            primary: "ui-icon-arrowreturnthick-1-s"
        }
    }); //Set style of import button.
  
});
function createButtonSearch(){
    $(function () {
        $("#button-search").button({
        icons: { primary: "ui-icon-search" }
        });
        $("#button-refresh").button({
        icons: { primary: "ui-icon-refresh" }
        });
    });

}
//

//Construct button by user 
function constructBtn(_len, _key){
var _arrRef ="";
    for(i=0;i<_len; i++){
                $("#button-"+_key+"-save"+(i+1)).button({
                icons: { primary: "ui-icon-disk" }
                /*text: false*/ 
                });
                $("#button-"+_key+"-reset"+(i+1)).button({
                icons: { primary: "ui-icon-refresh" }
                /*text: false*/ 
                });
    }
       
}
//
//---->Construct Button
/*
<div style='padding: 0pt 0.7em;' class='ui-state-error ui-corner-all'>
	<p>
		<span style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></span>
		<strong>Alert:</strong> Sample ui-state-error style.
	</p>
</div>
*/
//Global function
function validateUrl(_url){
var Reg = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
return Reg.test(_url);
}

function getDates(id) {
    var reg = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
    if (document.getElementById(id).value.match(reg)) {
        return true;
    } else {
        return false;
    }

}

function validateTime(_id) {
    var _regTime = /(\d{2}):(\d{2})/;
    if (document.getElementById(_id).value.match(_regTime)) {
        return true;
    } else {
        return false;
    }
}
     
/*
function setkey(ee){
    var _k=ee.keyCode;
    alert(_k);

    ee.keyCode=0

    return 0;

}  //onkeypress=return setkey(event)
    */  
function getPeriodTime(id) {
    var nlengh = document.getElementById(id).value.length;
    for (var i = 0; i < nlengh; ++i) {
        var ni = document.getElementById(id).value.charAt(i);
        if (ni.match(/[^0-9]/)) {
            return false;
        }
    }
    return true;
}
//check empty field
function emptyField(textObj) {
    if (textObj.value.length == 0)
        return true;
    for (var i = 0; i < textObj.value.length; ++i) {
        var ch = textObj.value.charAt(i);
        if (ch != ' ' && ch != '	')
            return false;
    }
    return true;
}

//stamp row of table when click deleting button
function trapTr(_id, _i) {
    //document.getElementById(_id).rows[_i].disabled = true;
    document.getElementById(_id).rows[_i].style.backgroundColor = '#fae6c8'; // '#D9FFFF';
}
//unstamp row of table when click cancel button
function unTrapTr(_id, _i) {
    document.getElementById(_id).rows[_i].disabled = false;
    document.getElementById(_id).rows[_i].style.backgroundColor = ''; // '#D9FFFF';
}

//stamp row of table when click deleting button
function trapTrHard(_idCollection) {
    var _arrId = _idCollection.split("#");
    var _id = _arrId[0];
    var _i = _arrId[1];
    document.getElementById(_id).rows[_i].style.backgroundColor = '#fae6c8'; // '#D9FFFF';
    //document.getElementById(_id).rows[_i].disabled = true; // '#D9FFFF';
}
//unstamp row of table when click cancel button
function unTrapTrHard(_id, _i) {
    var _arrId = _idCollection.split("#");
    var _id = _arrId[0];
    var _i = _arrId[1];
    document.getElementById(_id).rows[_i].style.backgroundColor = ''; // '#D9FFFF';
    document.getElementById(_id).rows[_i].disabled = false; // '#D9FFFF';
}

    //stamp row of table when click check "check box"
function chkTr(_id, _i) {
    document.getElementById(_id).rows[_i].style.backgroundColor = '#FAE6C8'; // '##fae6c8';
    document.getElementById(_id).rows[_i].setAttribute('onmouseout', 'this.style.backgroundColor="#fae6c8"');
}
//unstamp row of table when click uncheck "check box"
function unChkTr(_id, _i) {
    document.getElementById(_id).rows[_i].style.backgroundColor = ''; // '#fae6c8';
    document.getElementById(_id).rows[_i].setAttribute('onmouseout', 'this.style.backgroundColor=""');
}

/****************************************Muti title function group*******************************************/
//Global var muti title
var _glob_strTitle = "เรื่อง";

function constructDelInput(_len){
var _arrtitle ="";
    for(i=0;i<_len; i++){
                $("#button-delete"+(i+1)).button({
                icons: { primary: "ui-icon-circle-minus" }/*text: false*/
                });
                _arrtitle += "#button-delete"+(i+1);
    }
    return _arrtitle;
}
function checkBtnDelInput(_len) {
    if (_len <= 1) {
        $("#button-delete").hide();
    } else {
        $("#button-delete").show();
    }
}

    //Add title
function appendTitle() {
    var _lenTitle;
    _lenTitle = $('.title').length;
        _latestTitleId = (parseInt((document.getElementsByName("title").item(_lenTitle-1).getAttribute("id")).substring(5))+1); //Find latest no of id
        $("#divTitle").append("<div id=\"specificField" + _latestTitleId + "\" style=\"padding:2px 0 2px 0;\"><input type=\"text\" name=\"title\" id=\"title" + _latestTitleId + "\" class=\"title\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\"><span class='specificField'>*</span>&nbsp;<button type=\"button\" id=\"button-delete"+(_latestTitleId)+"\" class=\"button_w30\" onclick=\"removeTitle("+_latestTitleId+")\"  title=\"ลบเรื่อง\"> </button></div>");
            var x= constructDelInput(_latestTitleId);
            //alert("Have Button=" + x + "Have lenTitle=" + _lenTitle);
       
}
function removeTitle(_lenTitleID) {
    $('#title' + (_lenTitleID)).remove();
    $('#specificField' + (_lenTitleID)).remove();
    _lenTitleAfter = $('.title').length;
    checkBtnDelInput(_lenTitleAfter);
       
}
   
function constructMultiTitle(_strTitle) {
    var _lenTitle;
    _lenTitle = $('.title').length;
    var _innerHtm = "";
    if ($("#trTitle").get(0)) {
        $("#trTitle").show();
    }
    _innerHtm = "<input type=\"hidden\" name=\"hid-btn-add-multi\" id=\"hid-btn-add-multi\">" + // hid-btn-add-multi keep to check mutititle or not in GetMultiInputValue (web.ashx)
                "<button type=\"button\" name=\"btn-add-multi\" id=\"button-add\" class=\"button_w30\" onclick=\"appendTitle()\" title=\"เพิ่ม\"> </button>";

    $("#divHeadTitle").html(_strTitle);
    _glob_strTitle = _strTitle.substr(0,(_strTitle.length)-1); //Set global string title

        $("#divModifyTitle").html(_innerHtm);
        checkBtnDelInput(_lenTitle);
        $("#button-add").button({
            icons: { primary: "ui-icon-circle-plus" }
            //text: false
        });
        $("#button-delete").button({
            icons: { primary: "ui-icon-circle-minus" }
            //text: false
        });
          
}
function chkTitle(_idTitle, _eStyleMessage, _id){
    var _arrTitle = new Array();


    //alert($("#trTitle").css('display') + "---" + $("#trETitle").css('display')); //Test IE8

    if (
        ($("#trETitle").css('display') != "none" && $("#trETitle").attr("style") != undefined) ||
        ($("#trTitle").css('display') != "none" && $("#trTitle").attr("style") != undefined) ||
        (($("#trTitle").attr("style") == undefined)/*academic title*/ && ($("#trETitle").attr("style") == undefined) /*academic eTitle*/)
        ) {
        _arrTitle = document.getElementsByName(_idTitle);
        //alert("total objects with name \"textfield\" = \n" + _arrTitle.length);
        var _lenTitle = $("." + _idTitle).length;
        var tmpTitle = new Array();
        var j = 0;
        for (i = 0; i < _arrTitle.length; i++) {
            if (emptyField(document.getElementsByName(_idTitle).item(i))) {
                tmpTitle[j] = i;
                j++;
                if (i == 0) {
                    _eStyleMessage += "#กรุณากรอก" + _glob_strTitle;
                } else {
                    _eStyleMessage += "#กรุณากรอก" + _glob_strTitle + "ที่ " + (i + 1);
                }
                if (i == (_lenTitle - 1)) {

                    _id += ((document.getElementsByName(_idTitle).item(i).getAttribute("id")) + " ");
                }
            }

        }
    }
    return (_eStyleMessage + "," + _id);
}
function initTitle(_titleHead) {
    var _labelTitle = (_titleHead == undefined) ? _glob_strTitle : _titleHead;
    _glob_strTitle = _labelTitle;
        $("#divTitle").html("<input type=\"text\" name=\"title\" id=\"title0\" class=\"title\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\" maxlength=\"255\"><span class='specificField'>*</span>");
        $("#divHeadTitle").html(_labelTitle + ": ");
        $("#divModifyTitle").html("");
        if ($("#trTitle").get(0)) {
            $("#trTitle").hide();
        }
}
//End add title

//Edit title
function appendETitle() {
    var _lenETitle;
    _lenETitle = $('.eTitle').length;
    _latestETitleId = (parseInt((document.getElementsByName("eTitle").item(_lenETitle-1).getAttribute("id")).substring(6))+1); //Find latest no of id
        $("#divETitle").append("<div id=\"eSpecificField" + _latestETitleId + "\" style=\"padding:2px 0 2px 0\"><input type=\"text\" name=\"eTitle\" id=\"eTitle" + _latestETitleId + "\" class=\"eTitle\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\" maxlength=\"255\"><span class='specificField'>*</span>&nbsp;<button type=\"button\" id=\"button-delete"+(_latestETitleId)+"\" class=\"button_w30\" onclick=\"removeETitle("+_latestETitleId+")\"  title=\"ลบเรื่อง\"> </button></div>");
            var x= constructDelInput(_latestETitleId);
    //  }
       
}
function removeETitle(_lenETitleID) {
        $('#eTitle' + (_lenETitleID)).remove();
    $('#eSpecificField' + (_lenETitleID)).remove();
    _lenETitleAfter = $('.eTitle').length;
    checkBtnDelInput(_lenETitleAfter);
       
}
function constructEditMultiTitle(_strTitle, _multiTitle){
    var _htmTitle="";
    var _arrTitle = new Array();
        _arrTitle = _multiTitle.split(',');
        //alert("test-"+_arrTitle.length+"-"+ _arrTitle);
       if ($("#trETitle")) {
            $("#trETitle").show();
        }
    for(i=0;i<_arrTitle.length;i++){
    var _iTitle = "";
    if(i!=0){
        _iTitle = "<button type=\"button\" id=\"button-delete"+(i)+"\" class=\"button_w30\" onclick=\"removeETitle("+i+")\"  title=\"ลบเรื่อง\"> </button>";
    }
        _htmTitle += "<div id=\"eSpecificField" + i + "\" style=\"padding:2px 0 2px 0\"><input type=\"text\" name=\"eTitle\" id=\"eTitle"+ i + "\" class=\"eTitle\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\" maxlength=\"255\" value=\""+_arrTitle[i]+"\"><span class='specificField'>*</span>&nbsp;"+_iTitle+"</div>";
    }
    $("#divETitle").html(_htmTitle);
        var _lenETitle;
    _lenETitle = $('.eTitle').length
        var x= constructDelInput(_lenETitle);
    var _innerHtm = "";
    _innerHtm = "<input type=\"hidden\" name=\"hid-btn-add-multi\" id=\"hid-btn-add-multi\">" + // hid-btn-add-multi keep to check mutititle or not in GetMultiInputValue (web.ashx)
                "<button type=\"button\" name=\"btn-add-multi\" id=\"button-add\" class=\"button_w30\" onclick=\"appendETitle()\" title=\"เพิ่มเรื่อง\"> </button>";
        $("#divEHeadTitle").html(_strTitle);
        $("#divEModifyTitle").html(_innerHtm);
        checkBtnDelInput(_lenETitle);

        $("#button-add").button({
            icons: { primary: "ui-icon-circle-plus" }
            //text: false
        });
        $("#button-delete").button({
            icons: { primary: "ui-icon-circle-minus" }
            //text: false
        });

       
}

function constructEditSigleTitle(_strTitle, _singleTitle){
    //alert("STR"+_singleTitle);
    var _htmTitle = "";
    _htmTitle += "<div id=\"eSpecificField0\" style=\"padding:2px 0 2px 0\"><input type=\"text\" name=\"eTitle\" id=\"eTitle0\" class=\"eTitle\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\" maxlength=\"255\" value=\""+_singleTitle+"\"><span class='specificField'>*</span></div>";
        $("#divETitle").html(_htmTitle);
}

function initETitle(_titleHead) {
    var _labelTitle = (_titleHead == undefined) ? _glob_strTitle : _titleHead;
    $("#divETitle").html("<input type=\"text\" name=\"eTitle\" id=\"eTitle0\" class=\"eTitle\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\"><span class='specificField'>*</span>");
    $("#divEHeadTitle").html(_labelTitle + ": ");
    $("#divEModifyTitle").html("");
    if ($("#trETitle")) {
        $("#trETitle").hide();
    }
}
//End edit title
    
function blockComm(e){
	code = e.keyCode ? e.keyCode : e.which;
	var code = window.event ? e.keyCode : e.which;
	var key = String.fromCharCode(code);
	reg = /\,/;
	return !reg.test(key);
}
    
/****************************************End muti title function group*******************************************/


/*******************************************Muti ref function group*********************************************/
function constructDelRef(_len){
var _arrRef ="";
    for(i=0;i<_len; i++){
                $("#button-delete-ref"+(i+1)).button({icons: { primary: "ui-icon-circle-minus" }/*text: false*/ });
                _arrRef += "#button-delete-ref"+(i+1);
    }
    return _arrRef;
}
function checkBtnDelRef(_len) {
    if (_len <= 1) {
        $("#button-delete-ref").hide();
    } else {
        $("#button-delete-ref").show();
    }
}
//Add Ref
function appendRef(_divRef) {
    var _htmRef;
    var _lenRef;
    _lenRef = $('.ref').length;
    //(_lenRef);
    _latestRefId = (parseInt((document.getElementsByName("ref").item(_lenRef-1).getAttribute("id")).substring(3))+1); //Find latest no of id
    _htmRef = "<div id=\"specificFieldRef" + _latestRefId + "\" style=\"padding:5px 0 2px 0;\"><input type=\"text\" name=\"ref\" id=\"ref" + _latestRefId + "\" class=\"ref\" style=\"width:300px; font-style:italic; color:#999;\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\"ลิงค์\"> ";
    _htmRef += "<input type=\"text\" name=\"refDec\"  maxlength=\"255\" style=\"width:280px; font-style:italic; color:#999;\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\"คำอธิบาย\">&nbsp;<button type=\"button\" id=\"button-delete-ref"+(_latestRefId)+"\" class=\"button_w30\" onclick=\"removeRef("+_latestRefId+")\"  title=\"ลบลิงค์อ้างอิง\"> </button></div>";
        
        _lenSpecificFieldRef = $('.specificFieldRef').length
        $("#"+_divRef).append(_htmRef);
            var x= constructDelRef(_latestRefId);
            // alert("Have Button=" + x + "Have lenTitle=" + _lenRef);
       
}

function removeRef(_lenRefID) {
    $('#ref' + (_lenRefID)).remove();
    $('#specificFieldRef' + (_lenRefID)).remove();
    _lenRefAfter = $('.ref').length;
    //checkBtnDelRef(_lenRefAfter);
       
}
   
function constructMultiRef(_divHeadRef, _divRef, _divModifyRef) {
    var _lenRef;
    _lenRef = $('.ref').length;
    var _innerHtm = "";
    _innerHtm = "<button type=\"button\" id=\"button-add-ref\" class=\"button_w30\" onclick=\"appendRef('"+_divRef+"')\" title=\"เพิ่มลิงค์อ้างอิง\"> </button>";
          
        $("#" + _divHeadRef).html("ลิงค์"+": ");
        $("#" + _divModifyRef).html(_innerHtm);
        //checkBtnDelRef(_lenRef);
        $("#button-add-ref").button({
            icons: { primary: "ui-icon-circle-plus" }
            //text: false
        });
        $("#button-delete-ref").button({
            icons: { primary: "ui-icon-circle-minus" }
            //text: false
        });
          
}
function chkUrlRef(_idRef, _eStyleMessage, _id){
    var _arrRef =  new Array();
    _arrRef = document.getElementsByName(_idRef);
    var _i_havErrorUrl = 0;
    for (i = 0; i < _arrRef.length; i++) {
        if((document.getElementsByName(_idRef).item(i).value != "" && document.getElementsByName(_idRef).item(i).value != "ลิงค์") && (validateUrl(document.getElementsByName(_idRef).item(i).value)==false)){
        _eStyleMessage +=  "#กรุณากรอกรูปแบบของลิงค์ในช่องที่ " + (i+1) + " ให้ถูกต้อง";
        _id += ((document.getElementsByName(_idRef).item(i).getAttribute("id")) + " ");
        _i_havErrorUrl++;
        }
    }
        return (_i_havErrorUrl + "," +_eStyleMessage + "," + _id);
}
function chkRepeatRef(_idRef, _eStyleMessage, _id){
    var _arrRef =  new Array();
    var _arrTmpRef =  new Array(); var _iTmpRef=0;
    var _tmpEStypeMessageTmp = "";
    _arrRef = document.getElementsByName(_idRef);
        for (i = (_arrRef.length-1); i >= 0; i--) {
        for(j = (_arrRef.length-1); j >= 0; j--){
                    if((document.getElementsByName(_idRef).item(i).value != "" && document.getElementsByName(_idRef).item(i).value != "ลิงค์") && (document.getElementsByName(_idRef).item(i).value == document.getElementsByName(_idRef).item(j).value) && (jQuery.inArray(document.getElementsByName(_idRef).item(i).value, _arrTmpRef)===-1) && (j<i)){
                        _tmpEStypeMessageTmp = "#ลิงค์ในช่องที่ " + (i+1) + " ซ้ำกันกับลิงค์ในช่องที่ " + (j+1) +"  กรุณากรอกใหม่" + _tmpEStypeMessageTmp;
                        _id += ((document.getElementsByName(_idRef).item(i).getAttribute("id")) + " ");
                        //j = _arrRef.length-1;
                        _arrTmpRef[_iTmpRef] = document.getElementsByName(_idRef).item(i).value;
                        _iTmpRef++;
                    }
                        
        }
        }
        _eStyleMessage += _tmpEStypeMessageTmp;
        return (_eStyleMessage + "," + _id);
}
function chkNullRef(_idRef, _eStyleMessage, _id){
    var _arrRef =  new Array();
    _arrRef = document.getElementsByName(_idRef);
    //alert("total objects with name \"textfield\" = \n" + _arrTitle.length);
        var _lenRef = $("."+_idRef).length;
        if( _arrRef.length > 1){
            var tmpRef = new Array();
            var j = 0;
            for (i = 0; i < _arrRef.length; i++) {
                if (emptyField(document.getElementsByName(_idRef).item(i)) || (document.getElementsByName(_idRef).item(i).value) == "ลิงค์") {
                    tmpRef[j] = i;
                    j++;
                    if (i == 0) {
                        _eStyleMessage += "#กรุณากรอกลิงค์อ้างอิง";
                    } else {
                        _eStyleMessage += "#กรุณากรอกลิงค์อ้างอิงที่ " + (i + 1);
                    }
                    if (i == (_lenRef - 1)) {
                        _id += ((document.getElementsByName(_idRef).item(i).getAttribute("id")) + " ");
                    }
                }
                   
            }
        }
}

        function chkRef(_idRef, _eStyleMessage, _id){
        /*
        var _rsRef = chkRef('ref', _eStyle.message, _id);
        var _arrRef = _rsRef.split(',');
        _eStyle.message = _arrRef[0];
        _id = _arrRef[1];
        var _rsUrlRef = chkUrlRef('ref', _eStyle.message, _id); //Repeat
        var _arrUrlRef = _rsUrlRef.split(',');
        var _i_havErrorUrl;
        _i_havErrorUrl = _arrUrlRef[0];
        _eStyle.message = _arrUrlRef[1];
        _id = _arrUrlRef[2];
        if (_i_havErrorUrl == 0) {
            var _rsRepeatRef = chkRepeatRef('ref', _eStyle.message, _id); //Repeat
            var _arrRepeatRef = _rsRepeatRef.split(',');
            _eStyle.message = _arrRepeatRef[0];
            _id = _arrRepeatRef[1];
        }
                    */
                var _rsUrlRef = chkUrlRef(_idRef, _eStyleMessage, _id);
                var _arrUrlRef = _rsUrlRef.split(',');
                var _i_havErrorUrl;
                _i_havErrorUrl = _arrUrlRef[0];
                _eStyleMessage = _arrUrlRef[1];
                _id = _arrUrlRef[2];
            if (_i_havErrorUrl == 0) {
                var _rsRepeatRef =  chkRepeatRef(_idRef, _eStyleMessage, _id); //Repeat
                var _arrRepeatRef = _rsRepeatRef.split(',');
                _eStyleMessage = _arrRepeatRef[0];
                _id = _arrRepeatRef[1];
            }
                _eStyleMessage = _eStyleMessage;
                _id = _id; 
        return (_eStyleMessage + "," + _id);
    }
function initRef(_divHeadRef, _divRef, _divModifyRef){
        var _htmRef;
        _htmRef = "<div style=\"padding:2px 0 2px 0;\"><input type=\"text\" name=\"ref\" id=\"ref0\" class=\"ref\" style=\"width:300px; font-style:italic; color:#999;\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\"ลิงค์\"> ";
        _htmRef += "<input type=\"text\" name=\"refDec\"  maxlength=\"255\" style=\"width:280px; font-style:italic; color:#999;\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\"คำอธิบาย\"></div>";
        $("#"+_divHeadRef).html("ลิงค์: ");
        $("#"+_divRef).html(_htmRef);
        $("#"+_divModifyRef).html("");
}
//End add ref
//Edit ref
function appendERef() {
    var _htmERef;
    var _lenERef;
    _lenERef = $('.eRef').length;
    _latestERefId = (parseInt((document.getElementsByName("eRef").item(_lenERef-1).getAttribute("id")).substring(4))+1); //Find latest no of id
    _htmERef = "<div id=\"specificFieldRef" + _latestERefId + "\" style=\"padding:5px 0 2px 0;\"><input type=\"text\" name=\"eRef\" id=\"eRef" + _latestERefId + "\" class=\"eRef\" style=\"width:300px; font-style:italic; color:#999;\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\"ลิงค์\"> ";
    _htmERef += "<input type=\"text\" name=\"eRefDec\"  maxlength=\"255\" style=\"width:280px; font-style:italic; color:#999;\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\"คำอธิบาย\">&nbsp;<button type=\"button\" id=\"button-delete-ref"+(_latestERefId)+"\" class=\"button_w30\" onclick=\"removeRef("+_latestERefId+")\"  title=\"ลบลิงค์อ้างอิง\"> </button></div>"
    //alert(_latestERefId);
        $("#divERef").append(_htmERef);
            var x= constructDelRef(_latestERefId);
    //  }
       
}

function createRef(){
        initRef("divHeadRef", "divRef", "divModifyRef");
        constructMultiRef("divHeadRef", "divRef", "divModifyRef") // Add  ref
        //alert('createRef');
}   

function removeERef(_lenERefID) {
        $('#eRef' + (_lenERefID)).remove();
    $('#eSpecificFieldRef' + (_lenERefID)).remove();
    _lenERefAfter = $('.eRef').length;
    checkBtnDelRef(_lenERefAfter);
       
}
function constructEditMultiRef(_strRef, _multiRef){

    var _htmRef="";
    var _arrMainRef = new Array();

    if(_multiRef != ""){
        _arrMainRef = _multiRef.split("<@>");
       
        for(i=0;i<_arrMainRef.length;i++){
            var _arrRef = new Array();
            var _arrURL = new Array();
            var _arrURLDec = new Array();
            var _iRef = "";
            var _addRefStyle = "";
            var _addRefDescStyle = "";
            _arrRef = _arrMainRef[i].split(",");
            _arrURL = _arrRef[0];
            _arrURLDec = _arrRef[1];
        
            //<div id=\"specificFieldRef" + _latestRefId + "\" style=\"padding:5px 0 2px 0;\">
            //<input type=\"text\" name=\"ref\" id=\"ref" + _latestRefId + "\" class=\"ref\" style=\"width:300px; font-style:italic; color:#999;\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\"ลิงค์\"><span class='specificField'>*</span> 
            //<input type=\"text\" name=\"refDec\"  maxlength=\"255\" style=\"width:280px; font-style:italic; color:#999;\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\"คำอธิบาย\">&nbsp;<button type=\"button\" id=\"button-delete-ref"+(_latestRefId)+"\" class=\"button_w30\" onclick=\"removeRef("+_latestRefId+")\"  title=\"ลบลิงค์อ้างอิง\"> </button></div>
            if(i!=0){
                _iRef = "<button type=\"button\" id=\"button-delete-ref"+(i)+"\" class=\"button_w30\" onclick=\"removeERef("+i+")\"  title=\"ลบเรื่อง\"> </button>";
            }
                if(_arrURL==""){
                    _addRefStyle = "font-style:italic;color:#999;";
                    _arrRef = "ลิงค์";
                }
                if(_arrURLDec==""){
                    _addRefDescStyle = "font-style:italic;color:#999;";
                    _arrURLDec = "คำอธิบาย";
                }
                _htmRef += "<div id=\"eSpecificFieldRef" + i + "\" style=\"padding:"+((i==0)?"2":"5")+"px 0 2px 0;\">";
                _htmRef += "<input type=\"text\" name=\"eRef\" id=\"eRef"+ i + "\" class=\"eRef\" style=\"width:300px;"+_addRefStyle+"\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\""+_arrURL+"\"> ";
                _htmRef += "<input type=\"text\" name=\"eRefDec\"  maxlength=\"255\" style=\"width:280px;"+_addRefDescStyle+"\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\""+_arrURLDec+"\">";
                _htmRef += "&nbsp;" + _iRef;
                _htmRef += "</div>";
        }
            $("#divERef").html(_htmRef);
            var _lenERef;
            _lenERef = $('.eRef').length
       
            var x= constructDelInput(_lenERef);
            var _innerHtm = "";
        _innerHtm = "<button type=\"button\" id=\"button-add-ref2\" class=\"button_w30\" onclick=\"appendERef()\" title=\"เพิ่มลิงค์อ้างอิง\"> </button>";

            $("#divEHeadRef").html(_strRef+": ");
            $("#divEModifyRef").html(_innerHtm);
            constructDelRef(_lenERef);
            $("#button-add-ref2").button({
                icons: { primary: "ui-icon-circle-plus" }
                //text: false
            });
    }else{
    initERef();
    }
       
}

/*
function constructEditSigleRef(_strRef, _singleRef){
    //alert("STR"+_singleRef);
    var _htmRef = "";
    _htmRef += "<div id=\"eSpecificField0\" style=\"padding:2px 0 2px 0\"><input type=\"text\" name=\"eRef\" id=\"eRef0\" class=\"eRef\" style=\"width:450px;\" onkeypress=\"return blockComm(event);\" value=\""+_singleRef+"\"><span class='specificField'>*</span></div>";
        $("#divERef").html(_htmRef);
}
*/
    function initERef(){
    var _htmERef;
    _htmERef = "<div style=\"padding:2px 0 2px 0;\"><input type=\"text\" name=\"eRef\" id=\"eRef0\" class=\"eRef\" style=\"width:300px; font-style:italic; color:#999;\" onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999'; this.value='ลิงค์';}\" onfocus=\"if(this.value=='ลิงค์')  {this.style.fontStyle='normal'; this.style.color='#000';this.value='';}\" value=\"ลิงค์\"> ";
    _htmERef += "<input type=\"text\" name=\"eRefDec\"  maxlength=\"255\" style=\"width:280px; font-style:italic; color:#999;\"  onkeypress=\"return blockComm(event);\" onblur=\"if(this.value=='') {this.style.fontStyle='italic'; this.style.color='#999';  this.value='คำอธิบาย';}\" onfocus=\"if(this.value=='คำอธิบาย')  {this.style.fontStyle='normal'; this.style.color='#000'; this.value='';}\" value=\"คำอธิบาย\"></div>";
    _innerHtm = "<button type=\"button\" id=\"button-add-ref2\" class=\"button_w30\" onclick=\"appendERef()\" title=\"เพิ่มลิงค์อ้างอิง\"> </button>";
    $("#divERef").html(_htmERef);
    $("#divEHeadRef").html("ลิงค์: ");
        $("#divEModifyRef").html(_innerHtm);
$("#button-add-ref2").button({
    icons: { primary: "ui-icon-circle-plus" }
    //text: false
});
}
//End ref
/****************************************End muti ref function group********************************************/


/*******************************************File Upload function*************************************************/
function getFileUploadDynamic(_PTId, _divFile) {
    $.ajax({
        url: "../files_process/filesHandler.ashx",
        type: "POST",
        data: "action=getFileUplaodDynamic&PTId=" + _PTId,
        charset: "tis-620",
        success: function (data) {
            $("#" + _divFile).html(data);
        }

    })
}
function deleteFileUpload(_fileId, _PTId, _fileName, _divFile) {
    if(confirm("คุณแน่ใจหรือไม่ ที่ต้องการลบไฟล์"+_fileName+"\n ยืนยันการลบไฟล์กดปุ่ม OK   ยกเลิกการลบไฟล์กดปุ่ม Cancel")==true){
        $.ajax({
            url: "../files_process/filesHandler.ashx",
            type: "POST",
            data: "action=deleteFileUpload&FileId=" + _fileId,
            charset: "tis-620",
            success: function (data) {
                //alert(data); //alert delete status  1=true , 0=false
                getFileUploadDynamic(_PTId, _divFile);
            }

        })
    }
}
    /*******************************************End file Upload function***********************************************/

/*******************************************Dialog message for process*************************************************/
/*Insert Update Dalete All mission
*/
function dialogMessage(_status, _message, _messageAfterOK, _iconStatus) {
   if(_iconStatus == undefined){
        _iconStatus = '';
    }
    var _imgError = '<img title="แจ้งข้อมูล" src="../images/png/48x48/process_warning(1).png" border="0" align="absmiddle"/>&nbsp;&nbsp;';
    if((_status.substring(0, 11) == "insert fail") || (_status.substring(0, 11) == "update fail")){
            _message = _imgError + _message;
    }
    $("#dialogProcess").html(_message);
    //tgReportDuplicateGeneral();
    $(function () {
        $("#dialog:ui-dialog").dialog("destroy");
        $("#dialogProcess").dialog({
            position: 'center',
            width: 'auto',
            minHeight: 'auto',
            height: 'auto',
            draggable: false,
            resizable: false,
            modal: true,
            //show: 'clip',
            //hide: 'clip',
            zIndex: 2200,
            title: 'รายงานสถานะ',
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                    if(_messageAfterOK != undefined){
                      growlUIByUser(_messageAfterOK, _iconStatus);
                    }

                }
            },
            close: function (event, ui) {
                if(_messageAfterOK != undefined){
                  growlUIByUser(_messageAfterOK, _iconStatus);
                }

            }

        });
        if ((_status.substring(0, 6)) == "update") {
            closeEDialog();
        }
    });

}
function dialogMessageCommonSelect(_json) {//data form ajax
    //_mode, _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, _fncCancel, _fncCancelParam, _icon48x48
    //var _dataSend = JSON.stringify(_data);
    //_dataRe = JSON.parse(data);
    var _dataRe, _mode, _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, _fncCancel, _fncCancelParam, _icon48x48;
    _dataRe = JSON.parse(_json);
    _mode = _dataRe.mode;
    _message = _dataRe.message;
    _divId = _dataRe.divId;
    _messageAfterOK = _dataRe.messageAfterOK;
    _fncOk = _dataRe.fncOk;
    _fncOkParam = _dataRe.fncOkParam;
    _fncCancel = _dataRe.fncCancel;
    _fncCancelParam = _dataRe.fncCancelParam;
    _icon48x48 = _dataRe.icon48x48;
    //alert("dialogMessageCommonMain(" + _mode + "," + _message + "," + _divId + "," + _messageAfterOK + "," + _fncOk + "," + _fncOkParam + "," + _fncCancel + "," + _fncCancelParam + "," + _icon48x48 + ")");
    dialogMessageCommonMain(_mode, _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, _fncCancel, _fncCancelParam, 'undefined', 'undefined', _icon48x48);
}
function dialogMessageCommonAlert(_message, _fncOk, _fncOkParam, _icon48x48) {
    //_message***
    if(_fncOk==undefined){_fncOk='undefined';}
    if (_fncOkParam == undefined) { _fncOkParam = 'undefined'; }
    if (_icon48x48 == undefined) { _icon48x48 = 'undefined'; }

    dialogMessageCommonMain('alert', _message, 'undefined', 'undefined', _fncOk, _fncOkParam, 'undefined', 'undefined', 'undefined', 'undefined', _icon48x48);
}

function dialogMessageCommon(_mode,_message,_divId,_messageAfterOK,_fncOk,_fncOkParam,_icon48x48, _title) { 
    //_mode*** {[default,fail],[0,1]}
    //_message***
    //_divId***
    var _check=false;
    switch(_mode){
        case"0":
        case"default":
            _check=true;
            _mode='default';
            break;
        case"1":
        case"fail":
            _check=true;
            _mode='fail';
            break;
        case "error":
            _check = true;
            _mode = 'error';
            break;
    }
    if(_check){
        if(_messageAfterOK==undefined){_messageAfterOK = 'undefined';}
        if(_fncOk==undefined){_fncOk='undefined';}
        if (_fncOkParam == undefined) { _fncOkParam = 'undefined'; }
        if (_icon48x48 == undefined) { _icon48x48 = 'undefined'; }
        dialogMessageCommonMain(_mode, _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, 'undefined', 'undefined', 'undefined', 'undefined', _icon48x48, _title);
    }else{
        alert('param mode ไม่ถูกต้อง\n//_mode*** {[default,fail],[0,1]}');
    }
}
function dialogMessageCommonConF(_message, _divId, _fncOk, _fncCancel, _messageAfterOK, _fncOkParam, _fncCancelParam, _trapTableId, _trapTrId, _icon48x48, _title) {
    //_message***
    //_divId***
    if(_fncOk == undefined) { _fncOk = 'undefined'; }
    if(_fncCancel == undefined) { _fncCancel = 'undefined'; }
    if(_messageAfterOK==undefined){_messageAfterOK='undefined';}
    if(_fncOkParam==undefined){_fncOkParam='undefined';}
    if(_fncCancelParam==undefined){_fncCancelParam='undefined';}
    if(_icon48x48 == undefined) { _icon48x48 = 'undefined'; }
    if(_trapTableId == undefined) { _trapTableId = 'undefined'; }
    if (_trapTrId == undefined) { _trapTableId = 'undefined'; }
    if (_title == undefined) { _trapTableId = 'undefined'; }
    dialogMessageCommonMain('conF', _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, _fncCancel, _fncCancelParam, _trapTableId, _trapTrId, _icon48x48, _title);
}
function dialogMessageCommonMain(_mode, _message, _divId, _messageAfterOK, _fncOk, _fncOkParam, _fncCancel, _fncCancelParam, _trapTableId, _trapTrId, _icon48x48, _title) {
    if (_mode == "error") { _mode = "fail"; if (_icon48x48 == 'undefined') { var _icon48x48 = 'process_warning(1)'; } }
    var _title = (_title == undefined) ? "รายงานสถานะ" : _title;
    var _iconStatus;
    switch (_mode) {
        case "default":
            if (_icon48x48 == 'undefined') { var _icon48x48 = 'info(4)'; }
            _iconStatus = '<img src="../images/png/48x48/' + _icon48x48 + '.png" border="0" align="absmiddle"/>&nbsp;&nbsp;';
            $("#" + _divId).html(_iconStatus + _message);
            $("#" + _divId).dialog({
                position: 'center',
                width: 'auto',
                minHeight: 'auto',
                height: 'auto',
                //draggable: false,
                resizable: false,
                modal: true,
                //show: 'clip',
                //hide: 'clip',
                zIndex: 2200,
                title: _title,
                buttons: {
                    Ok: function () {
                        $(this).dialog("close");
                        if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                        if (_fncOk != 'undefined') { window[_fncOk](_fncOkParam); }
                    }
                },
                close: function (event, ui) {
                    if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                }
            });
            break;
        case "fail":
            if (_icon48x48 == 'undefined') { var _icon48x48 = 'warning(3)'; }
            _iconStatus = '<img src="../images/png/48x48/' + _icon48x48 + '.png" border="0" align="absmiddle"/>&nbsp;&nbsp;';
            $("#" + _divId).html(_iconStatus + _message);
            $("#" + _divId).dialog({
                position: 'center',
                width: 'auto',
                minHeight: 'auto',
                height: 'auto',
                //draggable: false,
                resizable: false,
                modal: true,
                //show: 'clip',
                //hide: 'clip',
                zIndex: 2200,
                title: _title,
                buttons: {
                    Ok: function () {
                        if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                        if (_fncOk != 'undefined') { window[_fncOk](_fncOkParam); }
                        $(this).dialog("close");
                    }
                },
                close: function (event, ui) {
                    if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                }
            });
            break;
        case "conF":
            if (_icon48x48 == 'undefined') { var _icon48x48 = 'help'; }
            _iconStatus = '<img src="../images/png/48x48/' + _icon48x48 + '.png" border="0" align="absmiddle"/>&nbsp;&nbsp;';
            $("#" + _divId).html(_iconStatus + _message);
            $("#" + _divId).dialog({
                position: 'center',
                width: 'auto',
                minHeight: 'auto',
                height: 'auto',
                //draggable: false,
                resizable: false,
                modal: true,
                //show: 'clip',
                //hide: 'clip',
                zIndex: 2200,
                title: _title,
                buttons: {
                    Ok: function () {
                        if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                        if (_fncOk != 'undefined') { var _boolRs =  window[_fncOk](_fncOkParam); }
                        if (_trapTableId != 'undefined') { unTrapTr(_trapTableId, _trapTrId); }
                        if (_boolRs == false) { return false; } else { $(this).dialog("close"); }
                       
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                        if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                        if (_fncCancel != 'undefined') { window[_fncCancel](_fncCancelParam); }
                        if (_trapTableId != 'undefined') { unTrapTr(_trapTableId, _trapTrId); }
                    }
                }/*,
                close: function (event, ui) {
                    if (_messageAfterOK != 'undefined') { growlUIByUser(_messageAfterOK); }
                    if (_fncCancel != 'undefined') { window[_fncCancel](_fncCancelParam); }
                    if (_trapTableId != 'undefined') { unTrapTr(_trapTableId, _trapTrId); }
                }*/
            });
            if (_trapTableId != 'undefined') { setTimeout("trapTr('" + _trapTableId + "'," + _trapTrId + ")", 10); }
            break;
        case "alert":
            growlUIByUser(_message);
            if (_fncOk != 'undefined') { window[_fncOk](_fncOkParam); }
            break;
        default:
            window[_fncOk](_fncOkParam);
            break;
    }
}
    /*****************************************End dialog message for process***********************************************/

    /*******************************************Table for report duplicate*************************************************/
    /*-Without teaching field
*/
    function reportDuplicateGeneral(_message){ //Fix Json object = 2 index parameter (description, table)
    _objJson = JSON.parse(_message); 
    var _imgWarning = '<img title="เตือน" src="../images/png/48x48/warning(2).png" border="0" align="absmiddle"/>&nbsp;&nbsp;';
    var _rsReport = "";
    var _description = "";
    var _table = "";
    var _jDescription = _objJson.description;
    //_jDescription = '<div style="padding:5px; min-width:450px; text-align:left;">' + _jDescription + '</div><div style="padding:2px; text-align:left;"><a style="cursor:pointer; color:#666666;" id="tgDetail">+ รายละเอียด</a></div>';
    _description = _imgWarning + _jDescription;
    var _jTable = _objJson.table;
        _table += '<div id="tgDuplReport" style="padding:5px; min-width:450px; text-align:center;" ><table border="0" cellspacing="0" cellpadding="0" style="min-width:450px">';
        for(i = 0; i < _jTable.length; i++){
                _table += '<tr>';
                for(j=0; j < _jTable[0].length; j++){
                    if(i == 0){
                    if(j==0){ _title = "<strong>ลำดับ</strong>"; }else{ _title = "<strong>" + _jTable[i][j] + "</strong>"; }
                    }else{
                    if(j==0){ _title = _jTable[i][0];}else{_title =  _jTable[i][j];}
                    }
                    if(i==0){
                        _table += '<td style="border-bottom:1px solid #666;" align="left"><div style="padding:3px;">'+ _title +'</div></td>';
                    }else{
                        _table += '<td style="border-bottom: 1px dotted #999;" align="left"><div style="padding:3px;">'+ _title +'</div></td>';
                    }
                }
                _table += '</tr>';
        }
            _table += "</table></div>";
            _rsReport += _description;
            _rsReport += _table
        return _rsReport;
    }
    function tgReportDuplicateGeneral(){
        $('#tgDetail').toggle(function() {
                $('#tgDetail').html('- รายละเอียด');
                $('#tgDuplReport').show();
            }, function() {
                $('#tgDetail').html('+ รายละเอียด');
                $('#tgDuplReport').hide();
        });
            $('#tgDuplReport').hide();
    }
    /*****************************************End table for report duplicate**********************************************/


    /*Focus input object*/
    /* Move to css
    $(document).ready(function () {
        $("input[type='text'], input[type='password'], select, textarea").live("focus blur", function (e) {
            var el = $(this);
             setTimeout(function () {
                el.toggleClass("m_focused", el.is(":focus"));
             }, 1);
        });
       
    });
    */
/**/

//end global function

function webAjax(_url, _data, _function, _mode, _type) {
    //_url***
    //_data***
    if (_mode == undefined) { _mode = 'default'; }
    if (_type == undefined) { _type = 'POST'; }
    switch(_mode){
        case "default":
            $.ajax({
                type: _type,
                url: _url,
                data: _data,
                success: _function
            });
            break;
        case "return":
            var _txt = $.ajax({
                url: _url,
                global: false,
                type: _type,
                data: _data,
                dataType: "html",
                async: false,
                success: _function
            }
            ).responseText;
            return _txt;
            break;
    }
}
function webAjaxDialogMessageCommonVPreload(_url, _data) {
    postPreload("กำลังแก้ไขข้อมูล");
    $.ajax({
        type: 'POST',
        url: _url,
        data: _data,
        async: true,
        success: function (data) {
            dialogMessageCommonSelect(data);
        }
    });
}

function webAjaxDialogMessageCommon(_url, _data) {
    $.ajax({
        type: 'POST',
        url: _url,
        data: _data,
        async: false,
        success: function (data) {
            dialogMessageCommonSelect(data);
        }
    });
}

function webButton(_id,_icon) {
    $("#" + _id).button({
        icons: { primary: _icon }
    });
}

/*
    Khanoksin.sur   20130623

    เป็นส่วนของการจัดการแถบเหลือง (permission) ทั้งหมด
    - ใช้เลือกสิทธิ์ในการจัดการ เช่น ผู้ดูและ ธุรการ อาจารย์
    - เลือกคณะที่มีสิทธิ์ในการดูแล
    - เลือก อาจารย์ในความดูและเพื่อทำงานให้
    - จดจำการเลือกในการเปลี่ยนด้านด้านใหม่ไม่ต้องเลือกบ่อย
*/
function webPMZone() {//permission
    var _PMZoneType, _PMZoneFaculty, _PMZonePerson, _PMZoneFunctionSwitch, _PMZoneSystemTemp;
    _PMZoneType = $('input[name=PMZoneRadio]:checked').val();
    _PMZoneType = _PMZoneType.split("#MUWP#");
    _PMZoneTypeTxt = _PMZoneType[1];
    _PMZoneType = _PMZoneType[0];
    _PMZoneFaculty = $('#PMZone_SelectFaculty').val();
    _PMZonePermissionTemp = $('#PMZonePermissionTemp').html();
    _PMZoneSystemTemp = $('#PMZoneSystemTemp').html();
    _PMZoneFunctionSwitch = $('#PMZoneFunctionSwitch').html();
    _PMZoneTempDataTeach = JSON.parse($("#PMZoneTempDataTeach").html());

    //เช็ค autoComp เพื่อเครียค่าถ้าเคยเลือกไปแล้ว
    if (_webPMZoneAutoComP != null) { _webPMZoneAutoComP.disable(); }
    _webPMZoneAutoComP = null;

    //ตรวจสอบสิทธิ์ของผู้ใช้งานว่าเลือกอะไร อาจารย์ หรือ ผู้ดูแลและธุรการ
    if (_PMZoneTypeTxt == "teach") { //teacher

        postPreloadMain(); // preload before run form add mission

        //dis ช่องเลือกหน่วยงาน
        $("#PMZone_SelectFaculty").attr("disabled", true);

        //clare & dis ช่องเลือกบุคคลากร
        $('#PMZoneRadio_SelectPerson').val("");
        $('#PMZoneRadio_SelectPerson').attr("disabled", true);

        //ดึงข้อมูลสิทธิ์ของอาจารย์เพื่อเตรียมส่งให้ GUI
        var _data = $("#PMZoneTempDataTeach").html();
        _data = {
            PMZonePermissionTemp: _data
            , genFrom: "java"
        };
        $('#PMZonePermissionTemp').html(JSON.stringify(_data));

        getPmUI();
        
        //_data = JSON.parse(_data["PMZonePermissionTemp"]);
        //alert(_data);
        //alert(_data[0] + ":" + txtDeCode(_data[1]) + ":" + txtDeCode(_data[2]) + ":" + txtDeCode(_data[3]) + ":" + txtDeCode(_data[4]) + ":" + txtDeCode(_data[5]) + ":" + txtDeCode(_data[6]));

    } else {//admin, officer

        //ยกเลิก dis ช่องเลือกหน่วยงาน
        $("#PMZone_SelectFaculty").attr("disabled", false);

        //ตรวจสอบพันธกิจของหน่วยงาน
        switch (webPMZoneCheckRule(_PMZoneFaculty)) {
            case "True":

                //clare & dis ช่องเลือกบุคคลากร
                $('#PMZoneRadio_SelectPerson').val("");
                $('#PMZoneRadio_SelectPerson').attr("disabled", true);

                //ส่งค่าว่ายังไม่ได้เลือกหน่วยงานให้ GUI
                var _data = {
                    PMZonePermissionTemp: ["1", "", "", "", "", "", ""]
                };
                $('#PMZonePermissionTemp').html(JSON.stringify(_data));

                //ดึงค่าการจำของแถบเหลือง (permission) ออกมาเช็ค
                var _tmpPDIDAndPID = $("#PMZoneRadio_SelectPerson").attr("tmpPDIDAndPID");
                var _tmpFacultyID = $("#PMZoneRadio_SelectPerson").attr("tmpFacultySelectID");
                var _jsonTmpPDIDAndPID = (_tmpPDIDAndPID == undefined ? { PDId: null } : JSON.parse(_tmpPDIDAndPID));

                //เช็คว่าเจอค่าที่จำไว้ และ ผู้ใช้ยังไม่ได้เลือกเปลี่ยนหน่วยงานอื่น
                //var _reg = new RegExp("^" + txtDeCode(_PMZoneFaculty));
                //alert(_PMZoneFaculty + ":" + _tmpFacultyID);
                //alert(txtDeCode(_PMZoneFaculty) + ":" + txtDeCode(_tmpFacultyID));
                if ((_tmpPDIDAndPID != undefined) && (txtDeCode(_PMZoneFaculty) == txtDeCode(_tmpFacultyID))) {

                    webPMZoneAutoComP(_PMZoneSystemTemp, _PMZoneType, _PMZoneFaculty);

                    //ยกเลิก dis ช่องเลือกบุคคลากร
                    $('#PMZoneRadio_SelectPerson').attr("disabled", false);

                    //ดึงชื่อบุคลากรที่จำค่าไว้และใส่ลงใน ช่องเลือกบุคลากร
                    var _tmpName = $('#PMZoneRadio_SelectPerson').attr("tmpName")
                    $('#PMZoneRadio_SelectPerson').val(_tmpName);

                    webPMZoneSetPermissionTemp(_tmpPDIDAndPID, _PMZoneSystemTemp, _PMZoneType, _tmpName, _PMZoneFaculty);

                } else {
                    
                    //alert("True call webPMZoneClearSession");
                    webPMZoneClearSession();
                    webPMZoneAutoComP(_PMZoneSystemTemp, _PMZoneType, _PMZoneFaculty);

                    //เรียก fnc ของ GUI ที่ตั้งค่ามา
                    window[_PMZoneFunctionSwitch]();
                }

                break;
            case "None":

                //clare & dis ช่องเลือกบุคคลากร
                $('#PMZoneRadio_SelectPerson').val("");
                $('#PMZoneRadio_SelectPerson').attr("disabled", true);
                
                //ส่งค่าว่ายังไม่ได้เลือกหน่วยงานให้ GUI
                var _data = {
                    PMZonePermissionTemp: ["1", "", "", "", "", "", ""]
                };
                $('#PMZonePermissionTemp').html(JSON.stringify(_data));

                //alert("None call webPMZoneClearSession");
                webPMZoneClearSession();

                //เรียก fnc ของ GUI ที่ตั้งค่ามา
                window[_PMZoneFunctionSwitch]();

                break;
            case "False":

                //clare & dis ช่องเลือกบุคคลากร
                $('#PMZoneRadio_SelectPerson').val("");
                $('#PMZoneRadio_SelectPerson').attr("disabled", true);

                //ส่งค่าว่าหน่วยงานยังไม่มีพันธกิจให้ GUI
                var _data = {
                    PMZonePermissionTemp: ["2", "", "", "", "", "", ""]
                };
                $('#PMZonePermissionTemp').html(JSON.stringify(_data));

                //alert("False call webPMZoneClearSession");
                webPMZoneClearSession();

                //เรียก fnc ของ GUI ที่ตั้งค่ามา
                window[_PMZoneFunctionSwitch]();

                break;
            default:
                break;
        }
    }
}
/*
    Khanoksin.sur   20130623

    เช็คพันธกิจของหน่วยงานว่ามีหรือยัง

    _PMZoneFaculty  รหัส PDID แบบเข้ารหัส

    return
        None    ยังไม่ได้เลือกหน่วยงาน
        True    หน่วยงานที่เลือกมีพันธกิจ
        False   หน่วยงานที่เลือกยังไม่ได้กำหนดพันธกิจ
*/
function webPMZoneCheckRule(_PMZoneFaculty) {
    var _url, _data, _function;
    var _status;
    _url = "../permission/permission.ashx";
    _data = {
        action: "ajaxPMZoneCheckRule"
        , PMZoneFaculty: _PMZoneFaculty
    };
    _status = webAjax(_url, _data, null, "return");
    return _status;
}
/*
    Khanoksin.sur   20130623

    เป็นส่วนของการตั้งค่าให้ autoComp ทำงานในการเลือกบุคลากร
    โดยการพิมพ์แค่บางส่วนของ ชื่อ หรือ นามสกุล ของผู้ใช้งาน
    ในระบบที่มีการตั้ง permission ให้มีสิทธิ์เป็นอาจารย์ของหน่วยงานนั้นๆ

    _PMZoneSystem   รหัสของ sys ตาม DB
    _PMZoneType     สิทธิ์ที่ผู้ใช้งานเลือกเป็นตัวเลข เช่น ผู้ดูแล ธุรการ
    _PMZoneFaculty  รหัสของคณะ
*/
var _webPMZoneAutoComP = null;
function webPMZoneAutoComP(_PMZoneSystem, _PMZoneType, _PMZoneFaculty) {//permission
    $('#PMZoneRadio_SelectPerson').attr("disabled", false);
    $('#PMZoneRadio_SelectPerson').val('');
    var _url;
    _url = '../permission/permission.ashx?action=ajaxPMZoneAutoComP&PMZoneSystem=' + _PMZoneSystem +
            '&PMZoneType=' + _PMZoneType + 
            '&PMZoneFaculty=' + _PMZoneFaculty;
    _webPMZoneAutoComP = $('#PMZoneRadio_SelectPerson').autocomplete({ serviceUrl: _url });
    _webPMZoneAutoComP.setOptions({
        noCache: true,
        onSelect: function (value, data) {
            //alert(value +'####'+ data);
            //$('#PMZoneRadio_SelectPerson').val("webPMZoneAutoComP:" + data + ":" + _PMZoneSystem + ":" + _PMZoneType + ":" + value);
            //      PID             SYS                 ZoneType        Name
            var _PMZoneFaculty = $('#PMZone_SelectFaculty').val();
            webPMZoneSetPermissionTemp(data, _PMZoneSystem, _PMZoneType, value, _PMZoneFaculty);
        }
    });
    _webPMZoneAutoComP.enable();
}
function webPMZoneSetPermissionTemp(_dataJson, _PMZoneSystem, _PMZoneType, _Name, _PMzoneFacultySeleteTmp) {//permission
    postPreloadMain(); // preload before run form add mission
    var _url, _PMZonePId, _PMZoneFaculty, _data, _function, _fncOk;
    _dataJson = JSON.parse(_dataJson);
    _PMZonePId = _dataJson.PId;
    _PMZoneFaculty = _dataJson.PDId;
    _fncOk = $('#PMZoneFunctionSwitch').html();
    _url = "../permission/permission.ashx?action=ajaxPMZoneSetPermissionTemp";
    _data = {
        PMZonePId: _PMZonePId
        , PMZoneSystem: _PMZoneSystem
        , PMZoneType: _PMZoneType
        , PMZoneFaculty: _PMZoneFaculty
        , PMzoneName: _Name
        , PMzoneFacultySeleteTmp: _PMzoneFacultySeleteTmp
    }
    _function = function (data) {
        $('#PMZonePermissionTemp').html(data);
        window[_fncOk]();
    }
    webAjax(_url, _data, _function);
}
/*
    Khanoksin.sur   20130623

    clear ค่าการจำการเลือกค่าการทำงานของแถบเหลือง (permission)
*/
function webPMZoneClearSession(_status) {
    //alert("webPMZoneClearSession");
    var _url, _data, _function, _dataReturn;
    _url = "../permission/permissionModel.ashx";
    _data = {
        action: "webPMZoneClearSessionAjax"
    };
    _function = function () { };
    _status = webAjax(_url, _data, _function, "return");
}

function webPMMZone() {//permission managements
    var _pMMZoneSwitchFunction;
    _pMMZoneSwitchFunction = $('#pMMZoneSwitchFunction').html();
    if (_pMMZoneSwitchFunction!="") {
        window[_pMMZoneSwitchFunction]();
    }
}
function webPMMZoneSelectFac(_PDID) {//permission managements
    var _url, _data, _function, _pMMZoneStatus;
    _pMMZoneStatus = JSON.parse($('#pMMZoneStatus').html());
    _url = '../permission/permission.ashx?action=ajaxPMMZoneGetPermissionTmp';
    _data = 'PId=' + _pMMZoneStatus["PId"]
        + '&systemId=' + _pMMZoneStatus["systemId"]
        + '&PDId=' + _PDID;
    _function = function (data) {
        $('#pMMZoneStatus').html(data);
        //alert(data);
        webPMMZone();
    };
    webAjax(_url, _data, _function);
}


//Phase permissiton data
function parsePmToCharp() {
    var _information, _objJson, _pmData;
    var _pm = new Array();

    _information = $("#PMZonePermissionTemp").html();
    _objJson = JSON.parse(_information); // Parse json

    switch (_objJson.genFrom) {
        case "java"://gen from java JSON.stringify()
            _pm = JSON.parse(_objJson.PMZonePermissionTemp);
            break;
        default://gen from c#
            _pm = _objJson.PMZonePermissionTemp;
            break;
    }

    _pmData = _pm[0] + "." + _pm[1] + "." + _pm[2] + "." + _pm[3] + "." + _pm[4] + "." + _pm[5] + "." + _pm[6];
    return _pmData;
}

function getPmUI() {

    $("#divFrmTeachBasis").show(); //Global from permission basis

    //Teaching module and form to hide when do not select permissin
    if ($("#mainAccordion").get(0)) { //If it is teaching mission (mainAccordion == true)
        $("#mainAccordion").html("");
        _getFormFunction = "getAccordingTeaching";  // Show according (form assign and form insert) + (permission type)
        _formAdd = undefined;
    }

    if($("#divFrmAddTeach").get(0)){
      _getFormFunction = "getFormTeaching";
        _formAdd = "tabTeach";
    }
    if ($("#divFrmAddThesis").get(0)) { //Thesis
        _getFormFunction = "getFormThesis";
        _formAdd = "frmAddThesis";
    }
    if ($("#divFrmAddCommittee").get(0)) { //Teach_Committee - Manage_Committee
        _getFormFunction = "getFormCommittee";
        _formAdd = "frmAddCommittee"
    }
    if ($("#divFrmAddOther").get(0)) { //T_Other
        _getFormFunction = "getFormOther";
        _formAdd = "frmAddOther"

    }
    //

    /* Ressearch module and form to hide when do not select permission

    */
    if ($("#divFrmAddResearch").get(0)) { 
        _getFormFunction = "getFormResearch";
        _formAdd = "frmAddResearch"
    }
    //

    //Academic module and form to hide when do not select permission
    if ($("#divFrmAddAcademic").get(0)) { 
        _getFormFunction = "getFormAcademic";
        _formAdd = "frmAddAcademic"
    }
    //


    //Management module and form to hide when do not select permission
    if ($("#frmAddManagement").get(0)) {
        _getFormFunction = "getFormManagement";
        _formAdd = "frmAddManagement"
    }
    if ($("#frmAddOtherManage").get(0)) {
        _getFormFunction = "getFormOtherManage";
        _formAdd = "frmAddOtherManage"
    }
    //


    //Culture module and form to hide when do not select permission
    if ($("#frmAddCulture").get(0)) {
        _getFormFunction = "getFormCulture";
        _formAdd = "frmAddCulture";
    }
    //

    $("#showTable").html("");

    var _pmData = parsePmToCharp(); //<--web.js
    var _pm = _pmData.split(".");
    if (_formAdd != undefined) {
        $("#" + _formAdd).hide(); //Initial form each mission.
    }
    $("#divFrmTeachBasis").hide(); //Initial form basis.
    $("#divFrmTeachBasis2").hide(); //Initial form no mission.
    if (_pm[0] == "1") {  //status = 1 lock interface
        $("#divFrmTeachBasis").show();
        $("#divFrmTeachBasis2").hide(); //Initial form no mission.
        $.unblockUI();
    }else if(_pm[0] == "2") {
        $("#divFrmTeachBasis").hide(); //Initial form basis.
        $("#divFrmTeachBasis2").show();
        $.unblockUI();
    } else {
        //_fnc = function () {
            //<---- Preload preprocessing
            _HTMLPreprocess = "<div style='width: 920px; margin-top:20px; color:#2e6e9e; border:1px solid #c5dbec; border-radius: 5px; text-align:center; padding-top:50px; padding-bottom:50px; font-weight:bold; font-size:16px !important; background-color:#F1F7FC;'><IMG border=0 src='../images/icon/loading3.gif' height='48' align='absmiddle'>&nbsp;&nbsp;กำลังเตรียมข้อมูล</div>";
            $("#showTable").html(_HTMLPreprocess);
            //<---- Preload preprocessing

            window[_getFormFunction](_pmData); // getFormFunction contain un set preload//
            showTable(_pmData); //Un set preload when show table successed.
       // };


        //_fnc = function () { alert(55);}

        //_msi.missionShowItemTabMainZone({
        //    mode: false
        //    , tab: 0
        //}, _fnc);
    }
}

var TimeR = function () { };
TimeR.prototype.statusLoad = false;
TimeR.prototype.checkStaus = function (_fnc) {
    var _idTime = setInterval();
}

/** Dynamic mission level UI (Work and ListWork)
* - Including 2 procedule are insert procedule and editing procedure, each procedule include 2 function are getDynDdlCondition and getDynDdlConditionList
* - A id of div or HTM Interface must use global var (set var by user) in each script file  or  call fucntion position
* 
*/
/** Procedule #1 for insert mission UI
 * -Please set the variables at call function position as follows.
 *  var _globCropWork = ?
 *  var _globDivWork = ?
 *  var _globCropListWork = ?
 *  var _globDivListWork = "?
*/
function getDynDdlCondition(_frmRule, _frmRuleDesc, _val, _case, _fncDdlWork, _fncDdlWorklParam) {
    initTitle(_glob_strTitle); //<-- This is a common function
            var _arrVal = _val.split("#");
            $("#" + _frmRuleDesc).html(""); //Clear history data from "form rule description" before getDdlCondition executing
            if (_val == "-") {
                if (_case == '1') {
                    //////$("#CropThesisWork").hide(); $("#divThesisWork").html("");
                    //////$("#CropThesisListWork").hide(); $("#divThesisListWork").html("");

                    $("#" + _globCropWork).hide(); $("#" + _globDivWork).html("");  //Please set the golbal var in call fucntion position
                    $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position

                } else if (_case == '2') {
                    //////$("#CropThesisListWork").hide(); $("#divThesisListWork").html("");
                    $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position
                }
                showForm(_frmRule, _frmRuleDesc, _val, '', ''); //<-- This is a common function
                $("#" + _frmRule).html("");
            } else {
                if (_arrVal[1] == undefined) { //have parent mission (Work mission)
                    //////getDdlThesisWork("divThesisWork"); //<---Change to user defined function
                    window[_fncDdlWork](_fncDdlWorklParam)
                } else {
                    if (_case == '1') {

                        //////$("#CropThesisWork").hide(); $("#divThesisWork").html('');
                        //////$("#CropThesisListWork").hide(); $("#divThesisListWork").html("");

                        $("#" + _globCropWork).hide(); $("#" + _globDivWork).html("");  //Please set the golbal var in call fucntion position
                        $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position

                    } else if (_case == '2') {
                        //////$("#CropThesisListWork").hide(); $("#divThesisListWork").html("");
                        $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position
                    } 
                    showForm(_frmRule, _frmRuleDesc, _val, '', ''); //<-- This is a common function
                
                }
            }
          
        }

        function getDynDdlConditionList(_frmRule, _frmRuleDesc, _val, _case, _fncDdlListWork, _fncDdlListWorkParam) {
            initTitle(_glob_strTitle); //<-- This is a common function
            var _arrVal = _val.split("#");
            $("#" + _frmRuleDesc).html(""); //Clear history data from "form rule description" before getDdlCondition executing
            if (_val == "-") {
                if (_case == '2') {
                    ///// $("#CropThesisListWork").hide(); $("#divThesisListWork").html('');
                    $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position
                  }
                showForm(_frmRule, _frmRuleDesc, _val, '', '');
                $("#" + _frmRule).html("");
            } else {
                if (_arrVal[1] == undefined) { //have parent mission (Work mission)
                    /////getDdlThesisListWork("divThesisListWork");//<---Change to user defined function
                    window[_fncDdlListWork](_fncDdlListWorkParam);
                } else {
                    var _i_frmRuleDesc = _frmRuleDesc.substr((_frmRuleDesc.length - 1), 1);
                    if (_i_frmRuleDesc == 2) { //Check when list work was showed then selected work again
                        ////$("#CropThesisListWork").hide(); $("#divThesisListWork").html('');
                        $("#" + _globCropListWork).hide(); $("#" + _globDivListWork).html(""); //Please set the golbal var in call fucntion position
                    }
                    showForm(_frmRule, _frmRuleDesc, _val, '', '');
                }
            }
           
        }
        //End Procedule #1

    /** Procedule #2 for edit mission UI
    * -Please set the variables at call function position as follows.
        *  var _globDdlEWork = ?
        *  var _globCropEWork = ?
        *  var _globDivEWork = ?
        *  var _globCropEListWork = ?
        *  var _globDivEListWork = ?
    */
        function getDynDdlECondition(_frmERule, _frmERuleDesc, _val, _case, _selectedMSWId, _selectedMSLWId, _fncDdlEWork, _fncDdlEWorkParam, _fncDdlEListWork, _fncDdlEListWorkParam, _newTimeStart, _newTimeStop, _thThsHistPoint) {
         
            initETitle();  //Make sure to clear muti title when onchenge ddl //<-- This is a common function
            var _arrVal = _val.split("#");

            $("#" + _frmERuleDesc).html(""); //Clear history data from "form rule description" before getDdlCondition executing

            if (_val == "-") {
                if (_case == '1') {
                    ////$("#CropEThesisWork").hide();
                    ////$("#CropEThesisListWork").hide();
                    $("#" + _globCropEWork).hide();
                    $("#" + _globDivEWork).html("");

                    $("#" + _globCropEListWork).hide();
                    $("#" + _globDivEListWork).html("");
                } else if (_case == '2') {
                    ////$("#CropEThesisListWork").hide();
                    $("#" + _globCropEListWork).hide()
                    $("#" + _globDivEListWork).html("");
                }

                $("#" + _frmERule).html("");
                editForm(_frmERule, _frmERuleDesc, _val, _newTimeStart, _newTimeStop, _thThsHistPoint);
            } else {
                if (_arrVal.length == 1) { //If this level not rule (_arrVal!=[x]#[x]) then call work level

                    ////getDdlEThesisWork("divEThesisWork", _selectedMSWId, _selectedMSLWId, _newTimeStart, _newTimeStop, _thThsHistPoint);
                    window[_fncDdlEWork](_fncDdlEWorkParam, _selectedMSWId, _selectedMSLWId, _newTimeStart, _newTimeStop, _thThsHistPoint);
                }

                if (_arrVal[1] == undefined) {
                    if (_selectedMSLWId != 0) { //work
                        //Nothing
                        ///var _valChar = $("#ddlEThesisWork").val();
                        var _valChar = $("#" + _globDdlEWork).val();
                        getDynDdlEConditionList("frmERule", "frmERuleDescription3", _valChar, 3, _selectedMSWId, _selectedMSLWId, _fncDdlEListWork, _fncDdlEListWorkParam, _newTimeStart, _newTimeStop, _thThsHistPoint);
                    }
                } else {
                    if ($("#eRid").val() == _arrVal[1]) { //if(Current rule = Selected rule)
                        editForm(_frmERule, _frmERuleDesc, _val, $("#eInPutStart").val(), $("#eInPutStop").val(), $("#eInPutHistPoint").val());
                    } else {
                        editForm(_frmERule, _frmERuleDesc, _val, _newTimeStart, _newTimeStop, _thThsHistPoint);
                    }
                    if (_case == '1') {
                        ////$("#CropEThesisWork").hide();
                        ////$("#CropEThesisListWork").hide();
                        $("#" + _globCropEWork).hide();
                        $("#" + _globDivEWork).html("");

                        $("#" + _globCropEListWork).hide()
                        $("#" + _globDivEListWork).html("");

                    } else if (_case == '2') {
                        //// $("#CropEThesisListWork").hide();
                        $("#" + _globCropEListWork).hide()
                        $("#" + _globDivEListWork).html("");
                    }
                }
                getFileUploadDynamic($("#ePTId").val(), 'eFile_wrap_list'); //<-- This is a common function
            }
           
        }


        function getDynDdlEConditionList(_frmERule, _frmERuleDesc, _val, _case, _selectedMSWId, _selectedMSLWId, _fncDdlEListWork, _fncDdlEWorkListParam, _newTimeStart, _newTimeStop, _thThsHistPoint) {
            initETitle();  //Make sure to clear muti title when onchenge ddl //<-- This is a common function
           
            var _arrVal = _val.split("#");
            $("#" + _frmERuleDesc).html(""); //Clear history data from "form rule description" before getDdlCondition executing

            if (_val == "-") {
                if (_case == '2') {
                    ////$("#CropEThesisListWork").hide(); 
                    ////$("#divEThesisListWork").html('');
                    $("#" + _globCropEListWork).hide();
                    $("#" + _globDivEListWork).html("");
                 }

                $("#" + _frmERule).html("");
                editForm(_frmERule, _frmERuleDesc, _val, _newTimeStart, _newTimeStop, _thThsHistPoint);
            } else {
                if (_arrVal[1] == undefined) { //have parent mission (Work mission)

                    ////getDdlEThesisListWork("divEThesisListWork", _selectedMSLWId, _newTimeStart, _newTimeStop, _thThsHistPoint);
                    window[_fncDdlEListWork](_fncDdlEWorkListParam, _selectedMSLWId, _newTimeStart, _newTimeStop, _thThsHistPoint);

                } else {
                    if ($("#eRid").val() == _arrVal[1]) { //if(Current rule = Selected rule)
                        editForm(_frmERule, _frmERuleDesc, _val, $("#eInPutStart").val(), $("#eInPutStop").val(), $("#eInPutHistPoint").val());
                    } else {
                        editForm(_frmERule, _frmERuleDesc, _val, _newTimeStart, _newTimeStop, _thThsHistPoint);
                    }
                    var _i_frmERuleDesc = _frmERuleDesc.substr((_frmERuleDesc.length - 1), 1);
                    if (_i_frmERuleDesc == 2) { //Check when list work was showed then selected work again
                        ////$("#CropEThesisListWork").hide();
                        ////$("#divEThesisListWork").html('');
                        $("#" + _globCropEListWork).hide();
                        $("#" + _globDivEListWork).html("");
                    }

                }
                getFileUploadDynamic($("#ePTId").val(), 'eFile_wrap_list'); //<-- This is a common function
            }
           
        }
        //End Procedule #2

        /** End Dynamic mission **/



function txtEnCode(_txt){
    var _url, _data, _function;
    _url = "../web/web.ashx";
    _data = {
        action: "ajaxTxtEnCode"
        , txt: _txt
    };
    return webAjax(_url, _data, _function, "return");
}
function txtDeCode(_txt) {
    var _url, _data, _function;
    _url = "../web/web.ashx";
    _data = {
        action: "ajaxTxtDeCode"
        , txt: _txt
    };
    return webAjax(_url, _data, _function, "return");
}
function getPMInsert(){
 var _pmData = (parsePmToCharp()); //<--web.js: permission
    var _url, _data, _function;
    _url = "../web/web.ashx?action=getPMInsert&pmData=" + _pmData;
    _data = {
        action: "getPMInsert"
        ,pmData: _pmData
    };
      return webAjax(_url, _data, _function, "return");
 }

/* Load //Initial form any mission

*/
function loadMission(){
    webPMZone(); //Initial form teaching
}

/*Delete item of point common function
*/
//Show normal table
function dynamicWorkItem(_param) { //Called by Web.dialogMessageCommonAlert in Handler of each mission
    var _pmData = (parsePmToCharp()); //<--web.js: permission
    if (_param == "delete") {
        postPreload("กำลังลบข้อมูล"); // delete data progress
    }
    showTable(_pmData, _param/*status*/, ""/*message*/);
}

function radioChange(jsonParam) {
    //alert(_name);
    var _name = jsonParam[0];
    var _id = jsonParam[1];
    $('input:radio[name="' + _name + '"]').each(function () {  // Disable day checkbox only case 3
        if (_id == $(this).attr('id')) {
           
            $(this).attr('checked', 'checked');
        }else{
            $(this).removeAttr('disabled', 'disabled');
        }
    });
}
//Before deleting is saved
function delWorkItem(_JSONParam, _trapTableId, _trapTrId) { //Each JSON object Parameter(url, pointID, pointGroupID, [mission/work]ID) is created in each mission (Such as _url: TeachingHandler).
    //_JSONParam is parameters send to delete confirm function.
    //Split delete method to 2 part
    // + 1 delete one item (Case 1-2) one record
    // + 2 delete one item used to exist in the colleciton
    // + 3 delete one item or many item (all item) in the collection 
    //     - 3.1 delete one item
    //     - 3.2 delete all item
    var _objJSON = jQuery.parseJSON(_JSONParam);
    var _PTId = _objJSON.pointId;
    var _PTGId = _objJSON.pointGroupId;
    var _getItemExistInCollection = null;
    if (_PTGId != "") {
       _getItemExistInCollection = getItemExistInCollection(_PTId, _PTGId);
    }
    //alert(_gob_messageConfirmDeleteItem +","+ "dialogProcess" +","+  "confirmDelWorkItem" +","+   undefined +","+  undefined +","+  _JSONParam +","+  undefined +","+  _trapTableId +","+  _trapTrId +","+  undefined +","+  "ยืนยันการลบข้อมูล");
    if (_PTGId == "" && _getItemExistInCollection == null) { //1
        //alert("1");
        dialogMessageCommonConF(_gob_messageConfirmDeleteItem, "dialogProcess", "confirmDelWorkItem", undefined, undefined, _JSONParam, undefined, _trapTableId, _trapTrId, undefined, "ยืนยันการลบข้อมูล");
    } else if (_PTGId != "" && _getItemExistInCollection == false) { //2
       // alert("2");
            dialogMessageCommonConF(_gob_messageConfirmDeleteItem, "dialogProcess", "confirmDelWorkItem", undefined, undefined, _JSONParam, undefined, _trapTableId, _trapTrId, undefined, "ยืนยันการลบข้อมูล");
    } else if (_PTGId != "" && _getItemExistInCollection == true) { //3
       // alert("3");
        if (getManyItemInCollection(_PTGId) == false) {//3.1

            _messageConfirmDeleteItem = "<span style='font-weight:bold; font-size:14px;'>ยืนยันการลบรายการ</span><br/>" +
                                        "<div id='divFrmWorkRepeatConfirmDel'>" +
                                            "<div style='padding-left:30px; padding-top:5px; padding-bottom:10px'><strong>ยืนยัน</strong>การลบรายการ <strong>Click</strong> ที่ปุ่ม <strong>OK</strong>,&nbsp;&nbsp;&nbsp;&nbsp;<strong>ยกเลิก</strong>การลบรายการ <strong>Click</strong> ที่ปุ่ม <strong>Cancel</strong></div>" +
                                         "</div>";
            dialogMessageCommonConF(_messageConfirmDeleteItem, "dialogProcess", "confirmDelWorkItem", undefined, undefined, _JSONParam, undefined, _trapTableId, _trapTrId, undefined, "ยืนยันการลบข้อมูล");
        } else if (getManyItemInCollection(_PTGId) == true) {//3.2
            var _onC1 = ["workRepeatDel", "workRepeatDel1"];
            var _onC2 = ["workRepeatDel", "workRepeatDel2"];
            _messageConfirmDeleteItem = "<span style='font-weight:bold; font-size:14px;'>ต้องการลบเฉพาะรายการนี้ หรือรายการทั้งหมดที่เกิดซ้ำในชุดข้อมูลนี้</span><br/><br/>" +
                                "<div id='divFrmWorkRepeatConfirmDel'>" +
                                "<form name='frmWorkRepeatConfirmDel' id='frmRepeatConfirm'>" +
                                   "<div style='padding-left:30px; padding-top:5px; padding-bottom:5px'><input name='workRepeatDel' id='workRepeatDel1' type='radio' value='1'/>&nbsp;&nbsp;<a style='cursor:pointer;' onclick='radioChange(" + JSON.stringify(_onC1) + ")'>ลบเฉพาะรายการนี้ (รายการอื่น ๆ ในชุดข้อมูลนี้จะไม่ถูกลบ)</a></div>" +
                                   "<div style='padding-left:30px; padding-top:5px; padding-bottom:5px'><input name='workRepeatDel' id='workRepeatDel2' type='radio' value='2'/>&nbsp;&nbsp;<a style='cursor:pointer;' onclick='radioChange(" + JSON.stringify(_onC2) + ")'>ลบรายการทั้งหมดที่เกิดซ้ำ (รายการทั้งหมดในชุดข้อมูลนี้จะถูกลบทั้งหมด)</a></div>" +
                                   "<div id='frmWorkRepeatConfirmDelAlert' style='padding-left:30px; padding-top:5px; padding-bottom:5px'></div>" +
                                "</form>" +
                                "</div>";
            dialogMessageCommonConF(_messageConfirmDeleteItem, "dialogProcess", "beforeConfirmDelWorkCollection", undefined, undefined, _JSONParam, undefined, _trapTableId, _trapTrId, undefined, "ยืนยันการลบข้อมูล");
        }
    }
}




function beforeConfirmDelWorkCollection(_JSONParam) {

    if ($("#workRepeatDel1").get(0).checked == false && $("#workRepeatDel2").get(0).checked == false) {
        $("#frmWorkRepeatConfirmDelAlert").html("<span style='color:#FF0000'>*กรุณาเลือกเงื่อนไขการลบข้อมูล</span>");
        return false;
    } else {
        $("#frmWorkRepeatConfirmDelAlert").html("");
        if ($("#workRepeatDel1").get(0).checked == true) {
            confirmDelWorkItem(_JSONParam, 1);
        } else if ($("#workRepeatDel2").get(0).checked == true) {
            confirmDelWorkItem(_JSONParam, 2);
        } else {
            $("#frmWorkRepeatConfirmAlert").html("<span style='color:#FF0000'>*กรุณาเลือกเงื่อนไขการลบข้อมูล</span>");
            return false;
        }
    }
}


//Confirm to save deleting
function confirmDelWorkItem(_JSONParam, _typeCollection) {
    if (_typeCollection == undefined) {
        _typeCollection = "0";
    }
    //_JSONParam is parameters send to delete confirm function.
    var _objJSON = jQuery.parseJSON(_JSONParam);
    //alert(_JSONParam + "<br>" + _url + ", " + _pointId + ", " + _workId); //Test display data
    var _url = _objJSON.url + ".ashx";
    var _data = {//Each JSON object Parameter(url, pointID, pointGroupID, workID) is created in each mission (Such as _url: TeachingHandler).
        action: "delWorkItem"
        , typeCollection: _typeCollection
        , pointId: _objJSON.pointId
        , pointGroupId: _objJSON.pointGroupId
        , workId: _objJSON.workId
    }
    webAjaxDialogMessageCommon(_url, _data);
}




//<-----------------------------Date and Period Date Input Function
/* Date and Period Date Input Function
*
*/
var _grob_idDateInput = "#divDateInput";
function setIDDateInput(_id) {
    _grob_idDateInput = _id;
}

function setDateInput(_case, _operation, _startDate, _endDate) {
    var _oper = "";
    _oper = (_operation == "edit" || _operation == "E") ? "E" : "";
    switch (_case) {
        case 1:
            _gob_initStartDate = _startDate; //Initilize start date
            _gob_startDate = _startDate;
            break;
        case 2:
            _gob_initStartDate = _startDate; //Initilize start date
            _gob_startDate = _startDate;
            _gob_initEndDate = _endDate; //Initilize end date
            _gob_endDate = _endDate;
            break;
        case 3:
            _gob_initStartDate = _startDate; //Initilize start date
            _gob_startDate = _startDate;
            _gob_initEndDate = _gob_startDate; //Initilize end date
            _gob_endDate = _gob_startDate;//Edit 1 row 1 day from date collecitom _gob_endDate = _gob_startDate
            break;
    }
}
function setIndexDayInput(_indexDay) {
    _gob_indexDay = _indexDay
}

function checkDayInput(_operation) {
    var _rs = "";
    var _oper = "";
    if (_operation == "edit" || _operation == "E") {
        _oper = "E";
    } else {
        _oper = "";
    }
   
     _arrDay = $('input[name*="day' + _oper + '"]:checkbox');
     _arrDay[_gob_indexDay].checked = true;

     $('input[name*="day' + _oper + '"]').each(function () {  // Disable day checkbox only case 3
         $(this).get(0).disabled = true;
     });

}

function checkChangePeriodDate() {
    $("#changeCollectionCheck").click(function () {
        if (document.getElementById('changeCollectionCheck').checked == false) {
            disabledDateInput(true, 3, "edit");
            postPreloadMain();
            loadFrmEdit(_gob_MSId);
        } else if (document.getElementById('changeCollectionCheck').checked == true) {
            disabledDateInput(false, 3, "edit");
            validatePeriodDateOfCaseDate3("edit", false);
        }
    });
};

function getDateInput(_case, _operation, _labelDateName1, _lableDateName2) {
    //alert(_case + ":" + _operation + ":" + _labelDateName1 + ":" + _lableDateName2);
  var _rsHTML = "";
  var _oper = "";
  if (_operation == "edit") {
      _oper = "E";
      _grob_idDateInput = "#divEDateInput";
  }else{
      _oper = "";
  }
  if (_labelDateName1 == undefined && _lableDateName2 == undefined) {
      var _rsHTML = "";
       if(_case == "1"){
         _labelDate1 = "วันที่ปฏิบัติงาน";
         _labelDate2 = null;
       }else if(_case == "2" || _case == "3"){
         _labelDate1 = "วันที่เริ่มต้น";
         _labelDate2 =  "วันที่สิ้นสุด";
       }else{
        _labelDate1 = "Unset";
        _labelDate2 = "Unset";
       }
  }else{
     if(_case == "1"){
         _labelDate1 = _labelDateName1;
         _labelDate2 = null;
       }else if(_case == "2" || _case == "3"){
         _labelDate1 = _labelDateName1;
         _labelDate2 = _lableDateName2;
       }else{
          _labelDate1 = "Unset";
          _labelDate2 = "Unset";
       }
  }
  var _HTMLChangeCollectionCheck = "&nbsp;&nbsp;&nbsp;&nbsp;<span style='padding-top:3px; padding-bottom:3px;  padding-left:10px; padding-right:10px;  background-color:#FF9;'><input type=\"checkbox\" name=\"changeCollectionCheck\" id=\"changeCollectionCheck\" /> เปลี่ยนแปลงช่วงวันที่ปฏิบัติงาน </span>";
  _rsHTML += "<div>" + 
             "<input type=\"hidden\" name=\"typeDateOper\" id=\"typeDateOper\" value=\"" + _oper + "\">" +
             "<input type=\"hidden\" name=\"case" + _oper + "Date\" id=\"case" + _oper + "Date\" value=\"" + _case + "\">" + // Use for add  or edit date
             "</div>";
    switch(_case){
        case 1:
            _rsHTML += "<table width=\"918\">" +
                        "<tr>" +
                            "<td width=\"200\" align=\"right\" valign=\"top\">" +
                                "<div class=\"textTopic\">" + _labelDate1 + ":</div>" +
                            "</td>" +
                            "<td width=\"700\">" +
                            "<div class=\"objectPadd\"  style=\"width:300px; float:left;\">" +
                                "<input type=\"text\" name=\"start" + _oper + "Date\" id=\"start" + _oper + "Date\" style=\"width: 70px;\">" +
                                "<span class='specificField'>*</span>" +
                            "</div>" +
                             "<div id=\"divEvalPeriod\" style=\"width:370px; padding-top: 2px; margin-right: 2px; float:left; text-align:right;\" >ช่วงเวลาเพิ่มข้อมูล ตั้งแต่วันที่ 1 เมษายน - 30 กันยายน 2556</div>" +
                            "<div id=\"divEvalPeriod\"></div>";
                            "</td>" +
                        "</tr>" +
                    "</table>";
            $(_grob_idDateInput).html(_rsHTML);
            getCalendar("#start" + _oper + "Date");
            $("#start" + _oper + "Date").val(_gob_startDate);
            break;
        case 2:
            _rsHTML += "<table width=\"918\">" +
                        "<tr>" +
                            "<td width=\"200\" align=\"right\" valign=\"top\">" +
                                "<div class=\"textTopic\">" + _labelDate1 + ":</div>" +
                            "</td>" +
                            "<td width=\"700\">" +
                            "<div class=\"objectPadd\" style=\"width:300px; float:left;\">" +
                                "<input type=\"text\" name=\"start" + _oper + "Date\" id=\"start" + _oper + "Date\" style=\"width: 70px;\">" +
                                "<span class='specificField'>*</span>" +
                                "&nbsp;&nbsp;&nbsp;<strong>" + _labelDate2 + ": </strong>" +
                                "<input type=\"text\" name=\"end" + _oper + "Date\" id=\"end" + _oper + "Date\" style=\"width: 70px;\">" +
                                "<span class='specificField'>*</span>" +
                            "</div>" +
                             "<div id=\"divEvalPeriod\" style=\"width:370px; padding-top: 2px; margin-right: 2px; float:left; text-align:right;\" >ช่วงเวลาเพิ่มข้อมูล ตั้งแต่วันที่ 1 เมษายน - 30 กันยายน 2556</div>" +
                            "</td>" +
                        "</tr>" +
                    "</table>";
            $(_grob_idDateInput).html(_rsHTML);
            getCalendar("#start" + _oper + "Date");
            getCalendar("#end" + _oper + "Date");
            $("#start" + _oper + "Date").val(_gob_startDate);
            $("#end" + _oper + "Date").val(_gob_endDate);
            break;
        case 3:
            _rsHTML += "<table width=\"918\">" +
                        "<tr>" +
                            "<td width=\"200\" align=\"right\" valign=\"top\">" +
                                "<div class=\"textTopic\">" + _labelDate1 + ":</div>" +
                            "</td>" +
                            "<td width=\"700\">" +
                            "<div class=\"objectPadd\" style=\"width:300px; float:left;\">" +
                                "<input type=\"text\" name=\"start"+_oper+"Date\" id=\"start"+_oper+"Date\" style=\"width: 70px;\">" +
                                "<span class='specificField'>*</span>" +
                                "&nbsp;&nbsp;&nbsp;<strong>" + _labelDate2 + ": </strong>" +
                                "<input type=\"text\" name=\"end"+_oper+"Date\" id=\"end"+_oper+"Date\" style=\"width: 70px;\">" +
                                "<span class='specificField'>*</span>" +
                            "</div>" +
                             "<div id=\"divEvalPeriod\" style=\"width:370px; padding-top: 2px; margin-right: 2px; float:left; text-align:right;\" >ช่วงเวลาเพิ่มข้อมูล ตั้งแต่วันที่ 1 เมษายน - 30 กันยายน 2556</div>" +
                           "</tr>" +
                           "<tr>" +
                            "<td width=\"200\" align=\"right\" valign=\"top\">" +
                                "<div class=\"textTopic\">" + "วันซ้ำ" + ":</div>" +
                            "</td>" +
                             "<td width=\"700\">" +
                            "<div class=\"objectPadd\">" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Sun\" id=\"day" + _oper + "Sun\" />" +
                                "&nbsp;อาทิตย์&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Mon\" id=\"day" + _oper + "Mon\" />" +
                                "&nbsp;จันทร์&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Tues\" id=\"day" + _oper + "Tues\" />" +
                                "&nbsp;อังคาร&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Wednes\" id=\"day" + _oper + "Wednes\"/>" +
                                "&nbsp;พุธ&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Thurs\" id=\"day" + _oper + "Thurs\" />" +
                                "&nbsp;พฤหัส&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Fri\" id=\"day" + _oper + "Fri\" />" +
                                "&nbsp;ศุกร์&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<input type=\"checkbox\" name=\"day" + _oper + "Satur\" id=\"day" + _oper + "Satur\" />" +
                                "&nbsp;เสาร์&nbsp;&nbsp;&nbsp;&nbsp;<!--<span class='specificField'>*</span>-->" +
                                ((_oper == "E") ? _HTMLChangeCollectionCheck : "") +
                             "</div>" +
                            "</td>" +
                        "</tr>" +
                    "</table>";     
            $(_grob_idDateInput).html(_rsHTML);
            getCalendar("#start" + _oper + "Date");
            getCalendar("#end" + _oper + "Date");
            $("#start" + _oper + "Date").val(_gob_startDate);
            $("#end" + _oper + "Date").val(_gob_endDate);
            validatePeriodDateOfCaseDate3(_oper, false);
            break;
        default:
            _rsHTML = null;
            break;
     }
   
    //Return check day used to checked
    if (_oper == "" && _case == 3) {  //If case 3 when refresh rule select checkbox day return check day used to checked
        $('input[name*="day"]').click(function () {
            var _gob_bool_;
            if ($(this).get(0).checked == true) {
                _gob_arr_day[$(this).attr("id")] = true;
            } else {
                _gob_arr_day[$(this).attr("id")] = false;
            }
        });
    }
   
    $('input[name*="day"]').each(function () {
        $(this).get(0).checked = _gob_arr_day[$(this).attr("id")]; //Return check day used to checked
    });
    //End return check day used to checked
    if (_oper == "E" && _case == 3) {  //If case 3 block edit date and day

        disabledDateInput(true, 3, "edit"); // Disable end date only
        $('input[name*="start' + _oper + 'Date"]').datepicker("option", {
            onSelect: function () {
                $('input[name*="end' + _oper + 'Date"]').val($(this).val());
                _gob_startDate = $(this).val();
                _gob_endDate = $(this).val();
            }
        }); //
        $('input[name*="end' + _oper + 'Date"]').datepicker("option", {
            onSelect: function () {
                _gob_endDate = $(this).val();
            }
        }); //
        checkDayInput("edit");
        checkChangePeriodDate();
    }

    setNewDateCase(_case); //Set _gob_newDateCase for check changing input date on form edit data

}
function disabledDayInput(_bool, _operation, _clearCheck) {
    if (_clearCheck == undefined) { _clearCheck = true; }
    if (_operation == "edit" || _operation == "E") {
        _oper = "E";
    } else {
        _oper = "";
    }
    $('input[name*="day' + _oper + '"]').each(function () {  // Disable day checkbox only case 3
        if (_bool == true) {
            if (_clearCheck == true) { $(this).get(0).checked = false; }
            $(this).get(0).disabled = true;
        } else {
            $(this).get(0).disabled = false;
        }
    });
}
function disabledDateInput(_bool, _caseDate, _operation) {
    var _oper;
    if (_operation == "edit" || _operation == "E") {
        _oper = "E";
    } else {
        _oper = "";
    }

    try{
        if (_caseDate == 1 || _caseDate == 2 || _caseDate == 3) { // Disable date input all case
            $('input[name*="end' + _oper + 'Date"]').each(function () {
                if (_bool == true) {
                    $(this).datepicker('disable');
                } else {
                    $(this).datepicker('enable');
                    $("#start" + _oper + "Date").datepicker("option", "onSelect", function () { getDateProperties("#start" + _oper + "Date"); }); //If select enddate before
                    $("#end" + _oper + "Date").datepicker("option", "onSelect", function () { getDateProperties("#end" + _oper + "Date"); }); //If select startdate before
                }
            });
        }
;
        if (_caseDate == 3) {
            $('input[name*="day' + _oper + '"]').each(function () {  // Disable day checkbox only case 3
                if (_bool == true) {
                    $(this).get(0).disabled = true;
                } else {
                    $(this).get(0).disabled = false;
                }
            });
        }
        if (_bool == true) {
            $("#eType").attr('disabled', 'disabled');
            $("#eAllRecord").attr('disabled', 'disabled');
        } else {
            $("#eType").removeAttr('disabled', 'disabled');
            $("#eAllRecord").removeAttr('disabled', 'disabled');
        }

        return true;
    }
   
    catch(error)
    {
        return false;
    }

}

function disabledDdlInput(_bool, _operation) {
    var _oper;
    if (_operation == "edit") {
        _oper = "E";
    } else {
        _oper = "";
    }
    try {
            $('select[name*="ddl' + _oper + '"]').each(function () {  // Disable day checkbox only case 3
                if (_bool == true) {
                    $(this).attr('disabled', 'disabled');
                } else {
                    $(this).removeAttr('disabled', 'disabled');
                }
            });
         
        return true;
    }

    catch (error) {
        return false;
    }

}

function getDateProperties(_id) { 
    if (_id == "#startDate" || _id == "#startEDate") {
        _gob_startDate = $(_id).val();
    } else {
        _gob_endDate = $(_id).val();
    }
    //Statement for check period date less or more than a week.
    if (_id == "#startDate" || _id == "#endDate") { //If select startdate or endDate before
            validatePeriodDateOfCaseDate3("");
    } else {
        if (_id == "#startEDate" || _id == "#endEDate") {  //If select startEdate or endEDate before
                validatePeriodDateOfCaseDate3("E");
        }
    }

}


function validatePeriodDateOfCaseDate3(_oper, _clearCheck) { //Function for check period date less or more than a week.
    _oper = (_oper == "edit") ? "E" : _oper;

    disabledDayInput(true, _oper, _clearCheck); //Initial day input event disable = true when onload page or onchange date

    if (($("#start" + _oper + "Date").get(0) && $("#end" + _oper + "Date").get(0)) && ( !emptyField($("#start" + _oper + "Date").get(0)) && !emptyField($("#end" + _oper + "Date").get(0)) )) {
        var _arr_rs_period_date = getPeriodDateForm($("#start" + _oper + "Date").val(), $("#end" + _oper + "Date").val());
        var _caseDate = $("#case" + _oper + "Date").val();
        if ($("#case" + _oper + "Date").val() != "1") {  ///
            switch (_caseDate) {
                case "3":
                    if (_arr_rs_period_date[1] == "End date < Start date") {  //return false!
                        disabledDayInput(true, _oper, _clearCheck);
                    } else if ((_arr_rs_period_date[1] == "Least than one") || (_arr_rs_period_date[0] >= 1 && _arr_rs_period_date[0] < 6)) { //return false!
                        disabledDayInput(true, _oper, _clearCheck);
                    } else if (_arr_rs_period_date[0] >= 6) { // Period date between start and end date >= 1 week. return true!
                        disabledDayInput(false, _oper, _clearCheck);
                    }

            }


        } ///
    }
}
 
function validateAddDateInput(_message, _id, _operation, _uncheckAllSelectAll) {
    _uncheckAllSelectAll = (_uncheckAllSelectAll == undefined) ? true : false;
    var _oper = (_operation == undefined) ? "" : "E";
    if ($("#start" + _oper + "Date").get(0)) {
        if (emptyField(document.getElementById("start" + _oper + "Date"))) {
            _message += "#กรุณาเลือก" + _labelDate1;
            //_eStyle.field = obj.birthday;
            _id += "start" + _oper + "Date ";
        } else if (getDates("start" + _oper + "Date") == false) {
            _message += "#รูปแบบ"+_labelDate1+"ไม่ถูกต้อง";
            _id += "start" + _oper + "Date ";
        }
     }
    if ($("#end" + _oper + "Date").get(0)) {
        if (emptyField(document.getElementById("end" + _oper + "Date"))) {
            _message += "#กรุณาเลือก" + _labelDate2;
            //_eStyle.field = obj.birthday;
            _id += "end" + _oper + "Date ";
        } else if (getDates("end" + _oper + "Date") == false) {
             _message += "#รูปแบบ" + _labelDate2 + "ไม่ถูกต้อง";
             _id += "end" + _oper + "Date ";
        }
    }

    if($("#start" + _oper + "Date").get(0) && $("#end" + _oper + "Date").get(0) && !emptyField(document.getElementById("start" + _oper + "Date")) && !emptyField(document.getElementById("end" + _oper + "Date"))) {
        var _arr_rs_period_date = getPeriodDateForm($("#start" + _oper + "Date").val(), $("#end" + _oper + "Date").val());
        var _caseDate = $("#caseDate").val();
        if ($("#caseDate").val() != "1") {  ///
            switch (_caseDate) {
                case "2":
                    if ((_arr_rs_period_date[1] == "End date < Start date")) {
                        _message += "#กรุณาเลือก" + _labelDate2 + "ให้เท่ากับหรือมากกว่า" + _labelDate1;
                        _id += "end" + _oper + "Date ";
                    }
                    break;
                default:
                    if ((_arr_rs_period_date[1] == "End date < Start date")) {
                        _message += "#กรุณาเลือก" + _labelDate2 + "ให้เท่ากับหรือมากกว่า" + _labelDate1;
                        _id += "end" + _oper + "Date ";
                    }
                    break;
            }


        } ///

    }


    var 
    _checkDay = 0;

    $("input[name*='day']:checkbox").each(function () {
        if ($(this).get(0)) {
            _checkDay++; 
         }
     });

    if(_checkDay!=0){
        _arrDay = $("input[name*='day']:checkbox");
        _arrDayLength = _arrDay.length;
        _iDay = 0;

        for (i = 0; i < _arrDayLength; i++) {
            if (_arrDay[i].checked == true) {
                _iDay += 1;
            }
        }
        if (_uncheckAllSelectAll == false) {
        if (_iDay == 0) {
            _message += "#กรุณาเลือกวันซ้ำ อย่างน้อย 1 วัน";
            _id += "daySun ";
        }
    }
    }

    var _JSONValdateRs = '{"message": "'+_message+'", "id": "'+ _id+'"}';
    var _objJson = jQuery.parseJSON(_JSONValdateRs);
    return _objJson;
}

function validateEDateInput(_message, _id){
    if ($("#startEDate").get(0)) {
        if (emptyField(document.getElementById('startEDate'))) {
            _message += "#กรุณาเลือก" + _labelDate1;
            //_eStyle.field = obj.birthday;
            _id += "startEDate ";
        }else if (getDates('startEDate') == false) {
            _message += "#รูปแบบวันที่"+_labelDate1+"ไม่ถูกต้อง";
            _id += "startEDate ";
        }
     }
   if ($("#endEDate").get(0)) {
        if (emptyField(document.getElementById('endEDate'))) {
            _message += "#กรุณาเลือก" + _labelDate2;
            //_eStyle.field = obj.birthday;
            _id += "endEDate ";
        } else if (getDates('endEDate') == false) {
             _message += "#รูปแบบวันที่" + _labelDate2 + "ไม่ถูกต้อง";
            _id += "endEDate ";
        }
    }
    _arrDay = $("input[name*='day']:checkbox");
    _arrDayLength = _arrDay.length;
    _iDay = 0;

    for (i = 0; i < _arrDayLength; i++) {
        if (_arrDay[i].checked == true) {
            _iDay += 1;
        }
    }

    if (_iDay == 0) {
        _message += "#กรุณาเลือกวัน อย่างน้อย 1 วัน";
        _id += "dayESun ";
    }
    var _JSONValdateRs = '{"message": "' + _message + '", "id": "'+ _id+'"}';
     var _objJson = jQuery.parseJSON(_JSONValdateRs);
    return _objJson;
}
//----------------------------> End Date and Period Date Input Function

//<---------------------------Check changing input date on form edit data

var _gob_currentDateCase = null;
var _gob_newDateCase = null;
function setCurrentDateCase(_currentDateCase) { //Set _gob_currentDateCase for check changing input date on form edit data (Contrain to penFrmEdit[All Mission] function)
    _gob_currentDateCase = _currentDateCase;
}
function setNewDateCase(_newDateCase) {  //Set _gob_newDateCase for check changing input date on form edit data (Contrain to getDateInput function)
    _gob_newDateCase = _newDateCase;
}



function returnTrue(){
    return true;
}

function returnFalse() {
    return false;
}

function getItemExistInCollection(_PTId, _PTGId) {
    var _boolRs;
    $.ajax({
        url: "../web/web.ashx",
        type: "POST",
        data: "action=getItemExistInCollection&PTId=" + _PTId + "&PTGId=" + _PTGId,
        charset: "tis-620",
        async: false,
        success: function (data) {
            if (data == "true") {
                _boolRs = true;
            } else if (data == "false") {
                _boolRs = false;
            } else {
                _boolRs = data;
                alert(data);
            }
        }
    });
    return _boolRs;
}
///   Check item in the collection is time series (Date input case 3) (Use for delete item / edit method)
///   - Delete item must use getItemExistInCollection for check status (exist or not exist ) firstly after that use this method
function getManyItemInCollection(_PTGId) { //For check item in the collection if 1 item  return fase but many records return true
    var _boolRs;
    $.ajax({
        url: "../web/web.ashx",
        type: "POST",
        data: "action=getManyItemInCollection&PTGId=" + _PTGId,
        charset: "tis-620",
        async: false,
        success: function (data) {
            if (data == "true") {
                _boolRs = true;
            } else if (data == "false") {
                _boolRs = false;
            } else {
                _boolRs = data;
                alert(data);
            }
        }
    });
    return _boolRs;
}

function submitEditWork(_currentDateCase, _newDateCase, _frmEditName) { //Check value changing in input date on form edit data
    var _boolRs = false;
    var _onC1 = ["workRepeat", "workRepeat1"];
    var _onC2 = ["workRepeat", "workRepeat2"];
    _HTMLWorkRepeatConfirm = "<span style='font-weight:bold; font-size:14px;'>ต้องการแก้ไขเฉพาะรายการนี้ หรือรายการทั้งหมดที่เกิดซ้ำในชุดข้อมูลนี้</span><br/><br/>" +
                            "<div id='divFrmWorkRepeatConfirm'>" +
                            "<form name='frmWorkRepeatConfirm' id='frmRepeatConfirm'>" +
                               "<div style='padding-left:30px; padding-top:5px; padding-bottom:5px'><input name='workRepeat' id='workRepeat1' type='radio' value='1'/>&nbsp;&nbsp;<a style='cursor:pointer' onclick='radioChange(" + JSON.stringify(_onC1) + ")'>แก้ไขเฉพาะรายการนี้ (รายการอื่น ๆ ในชุดข้อมูลนี้จะไม่ถูกแก้ไข)</a></div>" +
                               "<div style='padding-left:30px; padding-top:5px; padding-bottom:5px'><input name='workRepeat' id='workRepeat2' type='radio' value='2'/>&nbsp;&nbsp;<a style='cursor:pointer' onclick='radioChange(" + JSON.stringify(_onC2) + ")'>แก้ไขรายการทั้งหมดที่เกิดซ้ำ (รายการทั้งหมดในชุดข้อมูลนี้จะถูกแก้ไข)</a></div>" +
                               "<div id='frmWorkRepeatConfirmAlert' style='padding-left:30px; padding-top:5px; padding-bottom:5px'></div>" +
                            "</form>" +
                            "</div>";
    _HTMLWorkNotRepeatConfirm = "<span style='font-weight:bold; font-size:14px;'>ยืนยันการแก้ไขเฉพาะรายการนี้ (รายการอื่น ๆ ในชุดข้อมูลนี้จะไม่ถูกแก้ไข)</span><br/><br/>" +
                                     "<div id='divFrmWorkNotRepeatConfirm'>" +
                                    "<div style='padding-left:30px; padding-top:5px; padding-bottom:5px'>ต้องการแก้ไขเฉพาะรายการนี้ Click ที่ปุ่ม \"Ok\"  หรือ ยกเลิกการแก้ไข  Click ที่ปุ่ม \"Cancel\"  </div><br/>" +
                                 "</div>";
    var _HTMLRepeat = "";

    if (_currentDateCase == 1 || _currentDateCase == 2) { // DateInput Case 1 - 2 
        _objSubmitFormEdit = document.forms[_frmEditName];
        submitEditWorkDateCase1_2(_objSubmitFormEdit);

    } else if (_currentDateCase == 3) { // DateInput Case 3 
        var _typeEdit;
        if (_gob_PTGStatus == 1 && ($("#changeCollectionCheck").get(0).checked == false)) {
            _typeEdit = 3; //Edit item to used to exist in the collection (Current, this item not exist in the collection)
        } else {
            if (_newDateCase == 3 && (_gob_initStartDate == _gob_startDate && _gob_startDate == _gob_endDate) && ($("#changeCollectionCheck").get(0).checked == false)) { //Not edit date (Not edit date start) 3.1(0) This item will exit from the collection or 3.1(1) edit all item in the collection
                _typeEdit = 1;
            } else if (_newDateCase == 3 && (_gob_initStartDate != _gob_startDate && _gob_startDate == _gob_endDate) && ($("#changeCollectionCheck").get(0).checked == false)) { //Edit date start; 3.2(0) This item will exit from the collection.
                _typeEdit = 2;
            } else if (_newDateCase == 3 && ($("#changeCollectionCheck").get(0).checked == true)) { //Change the time series (Edit this item to the new time series and fag delete old series)
                _typeEdit = 4;
            }
        }
        //alert(_typeEdit);
        //_param_type_JSONF = '{ "formEditName": "' + _frmEditName + '", "typeEdit":  "' + _typeEdit + '" }';
        _param_type_JSONF = {
            formEditName: _frmEditName
            , typeEdit: _typeEdit
        };
        var _PTGId = $("#ePTGId").val();
        switch (_typeEdit) {
            case 1:
                if (getManyItemInCollection(_PTGId) == true) { //Collection type many item
                    //alert("Collection type many item");
                    dialogMessageCommonConF(_HTMLWorkRepeatConfirm, "dialogProcess", "submitEditWorkDateCase3", undefined, undefined, _param_type_JSONF, undefined, undefined, undefined, undefined, "ยืนยันการแก้ไขข้อมูล"); break;
                } else if (getManyItemInCollection(_PTGId) == false) {  //Collection type one item
                    //alert("Collection type one item");
                    submitEditWorkDateCase3(_param_type_JSONF);
                } else { //Error
                    alert(getManyItemInCollection(_PTGId));
                }
                break;
            case 2:
                dialogMessageCommonConF(_HTMLWorkNotRepeatConfirm, "dialogProcess", "submitEditWorkDateCase3", undefined, undefined, _param_type_JSONF, undefined, undefined, undefined, undefined, "ยืนยันการแก้ไขข้อมูล"); break;
            case 3: submitEditWorkDateCase3(_param_type_JSONF); break;
            case 4: submitEditWorkDateCase3(_param_type_JSONF); break;
            default: alert("EditWork function ERROR because does not meet the case of 'DateInput Type 3' ");
        }
    }

    

    // DateInput Case 1 or 2

    



    return _boolRs;
}
//------------------------->  End check changing input date on form edit data    

//<------------------------ Set Value before-Submit edit 
function submitEditWorkDateCase1_2(_frmEditName) {
    var _objSubmitEdit = new submitEdit();
    _objSubmitEdit.case1_2_eidtOneRecord(_frmEditName);
}

//Case date 3
function submitEditWorkDateCase3(_param_type_JSONF) { //_param_type_JSONF .formName and .typeEdit
    _obj_type_JSONF = _param_type_JSONF;
    var _formEditName = _obj_type_JSONF.formEditName;
    var _typeEdit = _obj_type_JSONF.typeEdit;
    _objSubmitFormEdit = document.forms[_formEditName];
    
    var _objSubmitEdit = new submitEdit();

    if (_typeEdit == 1) { // 3.1 [Date Case = 3; Type edit 1] (Not change start date)
        var _PTGId = $("#ePTGId").val();
        $("#eType").val("1");
        $("#frmWorkRepeatConfirmAlert").html("");
        if(getManyItemInCollection(_PTGId) == false){
            _objSubmitEdit.case3_editOneRecord(_objSubmitFormEdit); //3.1(0) [Date Case = 3; Type = 1; (eAllRecord = 0)] Edit this item in the collection
        }else{
            if ($("#workRepeat1").get(0).checked == false && $("#workRepeat2").get(0).checked == false ) {
                $("#frmWorkRepeatConfirmAlert").html("<span style='color:#FF0000'>*กรุณาเลือกเงื่อนไขการแก้ไขข้อมูล</span>");
                return false;
            } else {
                $("#frmWorkRepeatConfirmAlert").html("");
                if ($("#workRepeat1").get(0).checked == true) {
                    _objSubmitEdit.case3_editOneRecord(_objSubmitFormEdit); //3.1(0) [Date Case = 3; Type = 1; (eAllRecord = 0)] Edit this item in the collection but the item will exit from the collection
                } else if ($("#workRepeat2").get(0).checked == true) {
                    _objSubmitEdit.case3_editAllGroup(_objSubmitFormEdit);  //3.1(1) [Date Case = 3; Type = 1; (eAllRecord = 1)] Edit all item in the collection
                } else {
                    $("#frmWorkRepeatConfirmAlert").html("<span style='color:#FF0000'>*กรุณาเลือกเงื่อนไขการรแก้ไขข้อมูล</span>");
                    return false;
                }
            }
        }
    } //End Type edit 1

    if (_typeEdit == 2) { // 3.2 [Date Case = 3; Type edit 2] (Change start date)
        $("#eType").val("2");
        _objSubmitEdit.case3_editOneRecord(_objSubmitFormEdit); //3.2(0) [Date Case = 3; Type = 2; (eAllRecord = 0)] Edit this item in the collection but the item will exit from the collection
    }

    if (_typeEdit == 3) { // 3.3 [Date Case = 3; Type edit 3] Edit item to used to exist in the collection (Current, this item not exist in the collection)
        $("#eType").val("3");
        _objSubmitEdit.case3_editOneRecord(_objSubmitFormEdit);
    }

    if (_typeEdit == 4) {
        $("#eType").val("4");
        _objSubmitEdit.case3_editNewTimeSieries(_objSubmitFormEdit);
    }

}

var submitEdit = function () {
    this.case1_2_eidtOneRecord = function (_frmEditName) {
        disabledDdlInput(false, "edit");
        postPreload('กำลังแก้ไขข้อมูล'); // Modifying data status
        _frmEditName.submit();
        disabledDdlInput(true, "edit");
    }

    this.case3_editOneRecord = function(_frmEditName) { //Edit only opened record
        //alert("0");
        disabledDateInput(false, 3, "edit");
        disabledDdlInput(false, 3, "edit");
        $("#eAllRecord").val("0");
        postPreload('กำลังแก้ไขข้อมูล'); // Modifying data status
        _frmEditName.submit();
        disabledDateInput(true, 3, "edit");
        disabledDdlInput(true, "edit");
    }

    this.case3_editAllGroup = function(_frmEditName) { //Edit all record in collection or group
        //alert("1");
        disabledDateInput(false, 3, "edit");
        disabledDdlInput(false, "edit");
        $("#eAllRecord").val("1");
        postPreload('กำลังแก้ไขข้อมูลทุกรายการ'); // Modifying data progress
        _frmEditName.submit();
        disabledDateInput(true, 3, "edit");
        disabledDdlInput(true, "edit");
    }

    this.case3_editNewTimeSieries = function(_frmEditName) { //Add new time sieries and fag old time sieries
        disabledDateInput(false, 3, "edit");
        disabledDdlInput(false, "edit");
        $("#eAllRecord").val("1");
        postPreload('กำลังเปลี่ยนช่วงวันที่ใหม่'); // Modifying data progress
        _frmEditName.submit();
        disabledDateInput(true, 3, "edit");
        disabledDdlInput(true, "edit");
    }

    
}

   //End Case date 3
//-------------------------> End submit edit
//

//test 

//#################################################################################################
//  mission_showItem
//#################################################################################################

var mission_showItem = function () { }

mission_showItem.prototype.createTab = function () {
    //$("#missionShowItemTab").tabs();
}
//  jData(obj){
//      mode(bool)*         is hide;
//      tab(int)            0;  //0,1
//  }
//  fnc()                   for start
mission_showItem.prototype.missionShowItemTabMainZone = function (jData, fnc) {
    var _mode = (jData["mode"] == undefined ? true : jData["mode"]);
    var _tab = (jData["tab"] == undefined ? 0 : jData["tab"]);

    //this.missionShowItemTabMainZoneClear();
    if (_mode) {//hide
        $("#missionShowItemTabMainZone").hide();
    } else {//show
        $("#missionShowItemTab").tabs({ active: _tab });
        switch (_tab) {
            case 0:
                //fnc;
                break;
            case 1:
                break;
        }
        $("#missionShowItemTabMainZone").show();
    }
}
mission_showItem.prototype.missionShowItemTabMainZoneClear = function () {
    $("#missionShowItemTabDetail").html("");
    $("#missionShowItemTabGroupDetail").html("");
}

var _msi = new mission_showItem();

//#################################################################################################
//  mission_showItem end.
//#################################################################################################


//#################################################################################################
//  Show Item Report
//#################################################################################################
function showItemReport(level, _key, _tableWidth, _divId, _option, _row, _hour) {
    $.ajax({
        url: "userMission.ashx",
        type: "POST",
        async: false,
        data: "action=showItemReport&level=" + level + "&key=" + _key + "&tableWidth=" + _tableWidth + "&option=" + _option + "&row=" + _row + "&hour=" + _hour,
        charset: "tis-620",
        success: function (data) {
            $("#" + _divId).html(data);
        }
    });
}
//#################################################################################################
//   Show Item Report end
//#################################################################################################

/****************
*Class MassageBox
*****************/

function MessageBox() { }
MessageBox.prototype.title = "ข้อความจากระบบ";
MessageBox.prototype.ParseJSONMessageArr2HTM = function (_jsonMessage) {
    try{
        var _objJson = JSON.parse(_jsonMessage); // Parse json
        var _rsMassage = "";
        for (i = 0; i < _objJson.length; i++) {
            _rsMassage += _objJson[i] + "<br/>\n";
        }
    } catch (exec) {
        _rsMassage = _jsonMessage;
    }
    return _rsMassage;
}

MessageBox.prototype.Showing = function (_obj) {
    var _status = _obj.status;
    var _msg;
    var _title;


    switch(typeof (_obj.message))
    {
        case "object":
            _msg = this.ParseJSONMessageArr2HTM(_obj.message[0].text);
            _msg += ConvertJsonToTable(_obj.message[0].table, 'tableDupData', 'tableShow', null); break;
        case "string":
            _msg = this.ParseJSONMessageArr2HTM(_obj.message); break;
        default:
            _msg = this.ParseJSONMessageArr2HTM(_obj.message);
    }
    
    switch (_status)
    {
        case "success"      : _title = "นำเข้าข้อมูลสำเร็จ"; break;
        case "fail"         : _title = "แจ้งเตือน"; break;
        case "error"        : _title = "ระบบผิดพลาด"; break;
        case "duplicate"    : _title = "นำเข้าข้อมูลได้บางรายการ"; break;
        case "duplicates"   : _title = "ข้อมูลซ้ำซ้อน"; break;
        default             : _title = this.title;
    }
    $.unblockUI(); //<-- if BlockUI is showing then unblockUI.

    //Display dialog message
    if (_obj.status == "success") {
        dialogMessageCommon("fail", _msg, "dialog", { str: "นำเข้าข้อมูลสำเร็จ", icon: true }, undefined, undefined, undefined, _title);
    }else if (_obj.status == "duplicate") {
        dialogMessageCommon("fail", _msg, "dialog", { str: "นำเข้าข้อมูลได้บางรายการ", icon: true }, undefined, undefined, undefined, _title);
    }else if (_obj.status == "duplicates") {
        dialogMessageCommon("fail", _msg, "dialog", { str: "ไม่สามารถนำเข้าข้อมูลได้", icon: false }, undefined, undefined, undefined, _title);
    }else{
        dialogMessageCommon(_obj.status, _msg, "dialog", { str: "ไม่สามารถนำเข้าข้อมูลได้", icon: false }, undefined, undefined, undefined, _title);
    }
}

function myMessageBox(_obj) {
    var _messageBox = new MessageBox();
    _messageBox.Showing(_obj);

}
//End Class MassageBox

function processReport(_status, _message) {
    if (_status == "insert") { //Status insert
        getFormOther();
        _rsMessage = _message;
    } else if (_status == "insert fail") {
        _rsMessage = _message;
    } else if (_status == "insert duplicate") {
        //_rsMessage = "ข้อมูลการสอน(อื่นๆ) ที่เพิ่ม ซ้ำกับข้อมูลที่อยู่ในระบบ";
        _rsMessage = reportDuplicateGeneral(_message);
    } else if (_status == "update") {
        _rsMessage = _message;
    } else if (_status == "update fail") {
        _rsMessage = _message;
    } else if (_status == "update duplicate") {
        //_rsMessage = "ข้อมูลการสอน(อื่นๆ) ที่แก้ไข ซ้ำกับข้อมูลที่อยู่ในระบบ";
        _rsMessage = reportDuplicateGeneral(_message);
    } else {
        alert("Error: processSuccess! " + _status);
    }
    showTable(parsePmToCharp(), _status, _rsMessage);
}